Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a list of objects from Firebase DataSnapshot on android

I want to convert all Firebase DataSnapshot children to a list in android.

Something like this:

mFirebaseRef = new Firebase(FIREBASE_URL);  mFirebaseRef.addValueEventListener(new ValueEventListener() {     @Override     public void onDataChange(DataSnapshot dataSnapshot) {         List<String> td = (ArrayList<String>) dataSnapshot.getValue();         //notifyDataSetChanged();     }      @Override     public void onCancelled(FirebaseError firebaseError) {      } }); 
like image 334
Parth Vyas Avatar asked Oct 01 '15 11:10

Parth Vyas


2 Answers

I hope below code works

Firebase ref = new Firebase(FIREBASE_URL);    ref.addValueEventListener(new ValueEventListener() {       @Override       public void onDataChange(DataSnapshot snapshot) {           Log.e("Count " ,""+snapshot.getChildrenCount());           for (DataSnapshot postSnapshot: snapshot.getChildren()) {             <YourClass> post = postSnapshot.getValue(<YourClass>.class);             Log.e("Get Data", post.<YourMethod>());           }       }       @Override       public void onCancelled(FirebaseError firebaseError) {           Log.e("The read failed: " ,firebaseError.getMessage());       }   }); 
like image 100
Nilesh Senta Avatar answered Sep 28 '22 02:09

Nilesh Senta


Firebase stores a sequence of values in this format:

"-K-Y_Rhyxy9kfzIWw7Jq": "Value 1" "-K-Y_RqDV_zbNLPJYnOA": "Value 2" "-K-Y_SBoKvx6gAabUPDK": "Value 3" 

If that is how you have them, you are getting the wrong type. The above structure is represented as a Map, not as a List:

mFirebaseRef = new Firebase(FIREBASE_URL);  mFirebaseRef.addValueEventListener(new ValueEventListener() {     @Override     public void onDataChange(DataSnapshot dataSnapshot) {         Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();          List<Object> values = td.values();          //notifyDataSetChanged();     }      @Override     public void onCancelled(FirebaseError firebaseError) {      } }); 
like image 37
Frank van Puffelen Avatar answered Sep 28 '22 02:09

Frank van Puffelen