Search code examples
androidclassfirebasefirebase-realtime-databasesnapshot

Android Firebase DataSnapshot Cast to Class


I have a firebase database. When I get value from the snapshot, I have HashMap in below:

HashMap from the snap

and I have a Snap class like below. How can I cast the DataSnapshot to List of the class such as List<Snap> snapList = (HashMap<String,Object>) dataSnapshot.child(USER_PHONE).child("friends").getValue();

public class Snap {

    String key;
    String value;

    public  Snap(){

    }
    public Snap(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }
}

Solution

  • There is no way in Java in which you can cast a HashMap<String,Object> to a List<Snap>. What can you do instead, is to query your database and get all the Snap objects and then add them to a List<Snap>.

    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                Snap snap = ds.getValue(Snap.class);
                snapList.add(snap);
            }
        }
    
        @Override
        public void onCancelled(DatabaseError error) {
            Log.d("TAG", error.getMessage()); //Never ignore potential errors!
        }
    };
    yourRef.addListenerForSingleValueEvent(eventListener);