无法将字符串类型的对象转换为位图类型



好吧,因为没有人回答我,我再次询问有一些礼貌的人。。。我正在尝试检索上传到Firebase上的图像。在数据快照中,它会给出以下错误:Can't convert object of type java.lang.String to type android.graphics.Bitmap。我尝试了一些方法来解决这个问题,但没有任何改变。这是代码:

这是阅读帖子并将其显示在屏幕上的代码。

private void ReadPosts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("posts");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
postsList.clear();
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
Posts post = snapshot1.getValue(Posts.class);
for (String id : followingList) {
if (post.getPublisher().equals(id)) {
postsList.add(post);
}
}
}
postsAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}

这是型号代码。

public class Posts {
private Bitmap postImage;
private String postText;
private String publisher;
private String postId;

public Posts(Bitmap postImage, String postText, String publisher, String postId) {
this.postImage = postImage;
this.postText = postText;
this.publisher = publisher;
this.postId = postId;
}

public Posts() {
}

public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Bitmap getPostImage() {
return postImage;
}
public void setPostImage(Bitmap postImage) {
this.postImage = postImage;
}

public String getPostText() {
return postText;
}
public void setPostText(String postText) {
this.postText = postText;
}
}

这次请帮帮我。在论坛上没有任何帮助是没有意义的。。

问题是,数据库中的快照用字符串(可能是图像的链接(返回postImage,而在模型类中,postImage是用位图声明的。因此,无法将字符串直接转换为位图。因此,您必须更改模型类,如:

private Bitmap postImage;private String postImage;

然后你必须从链接加载图像(可能使用Glide(:

如果链接来自FirebaseStorage,您可以像这样加载图像:

StorageReference ref = storageReference.child(posts.postImage).getDownloadUrl();
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(ref)
.into(imageView);

如果链接来自图像的直接链接,你可以这样做:

Glide.with(this /* context */)
.load(posts.postImage)
.into(imageView);

注意:您需要Glide的等级依赖性:

implementation 'com.github.bumptech.glide:glide:4.12.0'

最新更新