Krishna Kumar Krishna Kumar - 2 months ago 16
Android Question

retieving data from firebase dynamically in android

I have my database structured like this in firebase:-


app root:
user:
uid1:
some data
uid2:
some data
helper:
helper1:
some data


and so on. I want to retrieve the data from this database. Only some specific data and display it in the app. Also I want download all the images(stored in the firebase storage) from the link provided in helper, and display them in app.

I have tried the documentation for retrieving the data but was unable to retrieve a specific list of data.

EDIT :-

private DatabaseReference myDb;
myDb = FirebaseDatabase.getInstance().getReference();

final String userId = getUid();
mDatabase.child("user").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {

public void onDataChange(DataSnapshot dataSnapshot) {

User uData = dataSnapshot.getValue(User.class);
}

});


This is what I learnt from documentation and was doing, it was good for a single valued data but I want to retrieve all the data under user category or helper.


  1. How do I iterate through all the data?

  2. How do I display a downloaded image from a link into an android app?



I hope it helps now.

Answer

Iterate over a list of Firebase nodes using dataSnapshot.getChildren() (should return an iterable irrc).

Example:

mDatabase.child("users").addListenerForSingleValueEvent(
   new ValueEventListener() {
       public void onDataChange(DataSnapshot dataSnapshot) {
           for (DataSnapshot childSnapshot : datasSnapshot.getChildren() {
               User uData = childSnapshot.getvalue(User.class);
           }
       }

       // onCancelled()...
    }
);

You display images in Android using ImageViews. I would recommend checking out the Square's Picasso Android image library for some useful functionality.