Reputation: 1118
I am trying to load an image from Firebase database into an ImageView for the user's profile picture.
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:
Thanks!
String url = FirebaseDatabase.getInstance().getReference("user/"+FirebaseAuth.getInstance().getCurrentUser().getUid().toString()+"/profilePicture").get().getResult().getValue().toString();
Upvotes: 0
Views: 100
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