无法从Firebase存储中检索图像

时间:2018-11-22 11:46:30

标签: android firebase android-recyclerview firebase-storage picasso

到目前为止,我已经成功地将图像上传到了Firebase,但是在将其检索到回收者视图时却遇到了问题,即图像根本没有被检索到。 看看我的源代码:

这是Recycler View适配器:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ImageViewHolder> {
Context mContext;
private List<Upload> mUploads;

public MyAdapter(Context context, List<Upload> uploads) {
    this.mContext = context;
    mUploads = uploads;
}

@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.layout_images, parent, false);
    return new ImageViewHolder(v);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getName());
    Picasso.get()
            .load(uploadCurrent.getImageUrl())
            .fit()
            .centerCrop()
            .into(holder.imageView);
}

@Override
public int getItemCount() {
    return mUploads.size();
}

public class ImageViewHolder extends RecyclerView.ViewHolder {
    public TextView textViewName;
    public ImageView imageView;

    public ImageViewHolder(View itemView) {
        super(itemView);

        textViewName = itemView.findViewById(R.id.text_view_name);
        imageView = itemView.findViewById(R.id.image_view_upload);
    }
}

这是我检索图像的主要班级:

public class Viewimages extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;



private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_viewimages);

    mRecyclerView = findViewById(R.id.recyclerView);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));


    mUploads = new ArrayList<>();

    mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");

    mDatabaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                Upload upload = postSnapshot.getValue(Upload.class);
                mUploads.add(upload);
            }

            mAdapter = new MyAdapter(Viewimages.this, mUploads);

            mRecyclerView.setAdapter(mAdapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(Viewimages.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();

        }
    });
}

In this image the image name is successfully fetched but inside the cardview images are not being populated

This the picture of database where url is stored

2 个答案:

答案 0 :(得分:2)

您什么也没得到,因为在您的实际数据库中您没有存储正确的图像URL,而是从内存中存储了某些对象的某些地址。因此,基本上,问题是当您上传图像并将URL保存到Firebase数据库时。因此,您应该将这些uri对象转换为String,以便可以正确存储它。

com.google.android.gms.tasks.zzu@13dd

不是有效的网址。

答案 1 :(得分:0)

正如@Alex所说,您没有存储有效的URL,这就是为什么您无法从数据库中检索那些图像的原因。

为了将URL从Firebase存储完美地存储到Firebase数据库,可以使用如下代码:

此代码还包含可将图像上传到Firebase存储器的部分,因此我认为这将使您与代码相关,甚至可能对您有所帮助。

private void uploadFile(Bitmap bitmap) {

        FirebaseStorage storage = FirebaseStorage.getInstance();
        final StorageReference storageRef = storage.getReference();

        final StorageReference ImagesRef = storageRef.child("images/"+mAu.getCurrentUser().getUid()+".jpg");


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] data = baos.toByteArray();
        final UploadTask uploadTask = ImagesRef.putBytes(data);



        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Log.i("whatTheFuck:",exception.toString());
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (!task.isSuccessful()) {
                            Log.i("problem", task.getException().toString());
                        }

                        return ImagesRef.getDownloadUrl(); 
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            Uri downloadUri = task.getResult();

                            DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getCurrentUser().getUid());

                            Log.i("seeThisUri", downloadUri.toString());// This is the one you should store

                            ref.child("imageURL").setValue(downloadUri.toString());


                        } else {
                            Log.i("wentWrong","downloadUri failure");
                        }
                    }
                });
             }
        });

    }

您可以在downloadUri.toString()的代码中看到的url,这是您应该存储在数据库中的URL。