我正在尝试从Firebase中加载图像到Recycler适配器并显示它们。我已经尝试了两种方法来解决这个问题。第一段代码的结果是错误信息“您无法在未附加视图或片段(其中getActivity()返回null,通常发生在在片段附加之前或片段被销毁后调用getActivity()时)上启动加载”。第二种方法应用程序运行,但没有图像被加载。通过阅读其他类似问题,我看到了isAdded()检查,但我无法使其工作。这些图像被上传到名为post_images的Firebase文件夹中,与帖子相关的其他数据(类似Instagram发布功能)存储在Firestore中。
我希望在Recycler View中显示图片。
public BlogRecyclerAdapter(List<BlogPost> blog_list) {
this.blog_list = blog_list;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
String desc_data = blog_list.get(position).getDesc();
holder.setDescText(desc_data);
String image_url = blog_list.get(position).getImage_url();
holder.setBlogImage(image_url);
}
@Override
public int getItemCount() {
return blog_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView descView;
private ImageView blogImageView;
public Context mContext;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDescText(String descText) {
descView = mView.findViewById(R.id.blog_desc);
descView.setText(descText);
}
public void setBlogImage(final String downloadUri) {
blogImageView = mView.findViewById(R.id.Post_image_view);
Glide.with(mContext).load(downloadUri).into(blogImageView);
}}}
尝试了其他方法
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mImageStorage = FirebaseStorage.getInstance().getReference();
final String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUserDatabase.keepSynced(true);
mUserDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
StorageReference filepath = mImageStorage.child("profile_images").child(current_uid + (".jpeg"));
Log.d("heere", "S");
// This gets the download url async
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
//The download url
final String downloadUrl = uri.toString();
Log.d("tag", downloadUrl);
if (!downloadUrl.equals("default")) {
Glide.with(mContext).load(downloadUrl).into(blogImageView);
// Glide.with(getApplicationContext()).load(downloadUrl).into(mDisplayImage);
}
}});}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});}}}
我希望在Recycler View中显示图片。