Rashi Sonowal Rashi Sonowal - 1 month ago 38
Android Question

Cannot read data in Firebase Database as list

The data in firebase is like the following

data image here

I want to get the data tagged as userId as list or an array.

my method is:

public static void writePostToFriends(final String userId, final String userName, final String title, final String body, final String authorPhoto){
DatabaseReference mpostRef = FirebaseDatabase.getInstance().getReference().child("social/user/"+userId+"/friends");
mpostRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<List<Friends>> t = new GenericTypeIndicator<List<Friends>>() {};
List<Friends> mFriends = dataSnapshot.getValue(t);
long j = mFriends.size();
for (long i = 0; i == j; i++){
Friends mReadFriends = dataSnapshot.getValue(Friends.class);
String getUid = mReadFriends.userID;
writeNewPost(getUid, userId, userName, title, body, authorPhoto);
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}


but when it try to read it gives this error -


Process: com.evolutionstudios.atmiyo, PID: 19506
com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap
at com.google.android.gms.internal.zzanp.zza(Unknown Source)
at com.google.android.gms.internal.zzanp.zza(Unknown Source)
at com.google.android.gms.internal.zzanp.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.evolutionstudios.atmiyo.Utils.NotificationHelper$1.onDataChange(NotificationHelper.java:40)
at com.google.android.gms.internal.zzakg.zza(Unknown Source)
at com.google.android.gms.internal.zzalg.zzcxk(Unknown Source)
at com.google.android.gms.internal.zzalj$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)


can anyone help me to figure out how to get the userID in the data as array or as a list?

Answer

The error message contains the gist of it:

Expected a List while deserializing, but got a class java.util.HashMap

If you look at your database, you see a collection of keys+values. In Java that translates to a Map and not to a List.

If you're only interested in the values, you need to handle the conversion from the Map to the List in your code:

public void onDataChange(DataSnapshot dataSnapshot) {
    GenericTypeIndicator<Map<String, Friends>> t = new GenericTypeIndicator<Map<String, Friends>>() {};
    Map<String, Friends> map = dataSnapshot.getValue(t);

    // get the values from map.values();

Or simpler:

public void onDataChange(DataSnapshot dataSnapshot) {
    List<Friends> list = new ArrayList<Friends>();
    for (DataSnapshot child: dataSnapshot.getChildren()) {
        list.add(child.getValue(Friends.class));
    }
}
Comments