Skip to content Skip to sidebar Skip to footer

Cannot Read Data In Firebase Database As List

The data in firebase is like the following I want to get the data tagged as userId as list or an array. my method is: public static void writePostToFriends(final String userId, f

Solution 1:

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:

publicvoidonDataChange(DataSnapshot dataSnapshot) {
    GenericTypeIndicator<Map<String, Friends>> t = newGenericTypeIndicator<Map<String, Friends>>() {};
    Map<String, Friends> map = dataSnapshot.getValue(t);

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

Or simpler:

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

Post a Comment for "Cannot Read Data In Firebase Database As List"