我正在尝试将图像从 firebase 获取到 recyclerview 中,但它没有显示我已将下载 URL 存储在模型类中,以便稍后检索它
并且规则也适用于实时数据库和存储
Java 文件
Search_Fragment.java
public class Search_Fragment extends Fragment {
public List<Upload> mUploads;
PostAdapter postsAdapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
RecyclerView postRecyclerView = view.findViewById(R.id.postRecyclerView);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
postRecyclerView.setLayoutManager(
new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
);
mUploads = new ArrayList<>();
postsAdapter = new PostAdapter(getContext(), mUploads);
postRecyclerView.setAdapter(postsAdapter);
//This are images that i tried manual ly and it worked fine
// List<PostItem> postItems = new ArrayList<>();
// postItems.add(new PostItem(R.drawable.image1));
// postItems.add(new PostItem(R.drawable.image2));
// postItems.add(new PostItem(R.drawable.image3));
// postItems.add(new PostItem(R.drawable.image4));
// postItems.add(new PostItem(R.drawable.image5));
// postItems.add(new PostItem(R.drawable.image7));
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Log.i("Sucess",upload.getmImageUrl());
mUploads.add(upload);
}
}
else {
Toast.makeText(getContext(),"Failure",Toast.LENGTH_SHORT).show();
}
//notify the adapter
postsAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
return view;
}
}
PostAdapter.Java //Apadter 类
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
public static List<Upload> mUploads;
Context mcontext;
public PostAdapter(Context context, List<Upload> uploads) {
mUploads = uploads;
mcontext = context;
}
@NonNull
@Override
public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(mcontext).inflate(R.layout.post_item_container, parent, false);
return new PostViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
Transformation transformation = new RoundedTransformationBuilder()
.borderColor(Color.WHITE)
.borderWidthDp(5)
.cornerRadiusDp(13)
.oval(false)
.build();
Log.i("sucess",uploadCurrent.getmImageUrl());
Picasso.get()
.load(uploadCurrent.getmImageUrl())
.fit()
.transform(transformation)
.into(holder.postImageView);
}
@Override
public int getItemCount() {
return mUploads.size();
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
RoundedImageView postImageView;
PostViewHolder(@NonNull View itemView) {
super(itemView);
postImageView = itemView.findViewById(R.id.imagePost);
}
}
}
Upload_Fragment.Java
public class Upload_Fragment extends Fragment {
private static final int PICK_IMAGE_REQUEST = 10;
private ImageView uploadImageView;
private Uri mImageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
private StorageTask mUploadTask;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_upload, container, false);
Button chooseImageButton = view.findViewById(R.id.upload_image_button);
Button uploadImageButton = view.findViewById(R.id.done_button);
uploadImageView = view.findViewById(R.id.upload_image_view);
storageReference = FirebaseStorage.getInstance().getReference("uploads");
databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
chooseImageButton.setOnClickListener(v -> openFileChooser());
uploadImageButton.setOnClickListener(v -> {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(getActivity(), "Upload in Progress", Toast.LENGTH_SHORT).show();
} else {
uploadToFirebase(mImageUri);
}
});
return view;
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(uploadImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = Objects.requireNonNull(getActivity()).getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void uploadToFirebase(Uri mImageUri) {
if (mImageUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
reference.putFile(mImageUri)
.addOnSuccessListener(taskSnapshot -> {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Saved Succesfully", Toast.LENGTH_SHORT).show();
reference.getDownloadUrl()
.addOnSuccessListener(uri -> {
Upload upload = new Upload(uri.toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
Log.i("Link", uri.toString());
});
})
.addOnProgressListener(snapshot -> {
double progress = (100.0 * snapshot.getBytesTransferred() / snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
})
.addOnFailureListener(e -> {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error Ocurred" + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
}
}
Upload.Java //模型类
public class Upload {
private String mImageUrl;
public Upload() {
}
public Upload(String imageUrl) {
this.mImageUrl = imageUrl;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
}
答案 0 :(得分:1)
看到要解决您的问题,需要调试一些事情,然后只有您才能解决问题。此外,您还需要澄清发生了什么。您可以尝试以下方法来获得解决方案。
1..将 Log
或 Toast
放入 for loop
中,同时将 url 添加到 mUploads
列表中。就像敬酒 upload.getmImageUrl()
并检查它是否给您正确http图片网址与否。
2.Put Log
或 Toast
在 Picasso 加载的图片 url 之前。Like toasting uploadCurrent.getmImageUrl()
并检查它是否为您提供了正确的 http 图片 url。
如果在敬酒时发生错误,将 toString();
放在最后。之后,您将有更好的想法来解决问题。
编辑:
在最重要的情况下,如果您获得正确的网址,则问题出在 Picasso
库上。您可以尝试使用 Glide
加载图像。为此添加
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
然后在 onBindViewHolder
侧像这样加载图像。
Glide.with(mContext).load(uploadCurrent.getmImageUrl()).into(holder.postImageView);
答案 1 :(得分:0)
Picasso.get()
.load(uploadCurrent.getmImageUrl())
.fit()
.transform(transformation)
.into(holder.postImageView);
你可以试试这个..也许吧?
Picasso.with(holder.postImageView)//or context
.load(uploadCurrent.getmImageUrl())
.fit()
.transform(transformation)
.into(holder.postImageView);