view raw
Rashi Sonowal Rashi Sonowal - 6 months ago 189
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() {
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);

public void onCancelled(DatabaseError databaseError) {


but when it try to read it gives this error -

Process: com.evolutionstudios.atmiyo, PID: 19506 Expected a List while deserializing, but got a class java.util.HashMap
at Source)
at Source)
at Source)
at Source)
at com.evolutionstudios.atmiyo.Utils.NotificationHelper$1.onDataChange(
at Source)
at Source)
at$ Source)
at android.os.Handler.handleCallback(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(

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


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()) {