ruchit patel
ruchit patel

Reputation: 77

Cannot retrieve images from firebase storage

So Far i have succeeded uploading images to firebase but while retrieving them to recycler view i'm facing problems i.e images are not being retrieved at all. Take a look at my source code:

This is Recycler View Adapter:

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);
    }
}

This is my main class to retrieve images:

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

Upvotes: 1

Views: 4385

Answers (2)

PradyumanDixit
PradyumanDixit

Reputation: 2375

Exactly as @Alex said, you're not storing the valid url, that's why you're not able to retrieve those images from the database.

For storing the url perfectly from your Firebase storage to your Firebase Database, you can use a code like this:

This code also contains the part where you can upload the image to your firebase storage, so I think this would make you relate to your code and may help you, even more.

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");
                        }
                    }
                });
             }
        });

    }

The url that you can see in the code from downloadUri.toString(), this is the one you should be storing in your database.

Upvotes: 2

Alex Mamo
Alex Mamo

Reputation: 138824

You aren't getting anything because in your actual database you aren't storing proper image urls but some addresses of some object from the memory. So basically the problem is when you are uploading the images and saving the urls to your Firebase database. So you should convert those uri objects to String, so it can be stored correctly.

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

Is not a valid url address.

Upvotes: 2

Related Questions