CodingChap
CodingChap

Reputation: 1118

How do I load an image from FirestoreDatabase into ImageView?

I am trying to load an image from Firebase database into an ImageView for the user's profile picture.

What I have tried

I have tried loading the image from Firestore to an ImageView using Glide. My code looks like this:

FirebaseDatabase.getInstance().getReference("user").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
        for (DataSnapshot child: snapshot.getChildren()) { 
                User user = child.getValue(User.class);
                Glide.with(MapsActivity.this).load(user.getProfilePicture()).error(R.drawable.ic_baseline_person_24).placeholder(R.drawable.ic_baseline_person_24).into(profileImage);

        }

    }

    @Override
    public void onCancelled(@NonNull @NotNull DatabaseError error) {
       throw error.toException();
    }
});

However, this isn't working.

My firebase structure is the following:

enter image description here

Thanks!

String url = FirebaseDatabase.getInstance().getReference("user/"+FirebaseAuth.getInstance().getCurrentUser().getUid().toString()+"/profilePicture").get().getResult().getValue().toString();

Upvotes: 0

Views: 100

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600130

You're loading the entire user node, which contains information for multiple users, so your snapshot contains the data for all of those users.

To handle those multiple users, you'll have to loop over snapshot.getChildren() in onDataChange:

FirebaseDatabase.getInstance().getReference("user").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
        for (DataSnapshot child: snapshot.getChildren()) { // 👈 loop over child snapshots
            User user = child.getValue(User.class);
            Log.i("DB", user.toString());
        }
    }
    @Override
    public void onCancelled(@NonNull @NotNull DatabaseError error) {
        throw error.toException(); // 👈 Never ignore errors
    }
});

If you know the UID of the user whose image you want to display, you can load just that user with:

                                                        // 👇 user to load
FirebaseDatabase.getInstance().getReference("user").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
        User user = child.getValue(User.class);
        Log.i("DB", user.toString());

    }
    @Override
    public void onCancelled(@NonNull @NotNull DatabaseError error) {
        throw error.toException(); // 👈 Never ignore errors
    }
});

You no longer need to loop over the getChildren() as now the code only loads a single user.

Upvotes: 1

Related Questions