Cannot read data in Firebase Database as list

后端 未结 1 1346
误落风尘
误落风尘 2020-12-29 14:03

The data in firebase is like the following

\"data

I want to get the data tagged as userId

相关标签:
1条回答
  • 2020-12-29 15:03

    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));
        }
    }
    
    0 讨论(0)
提交回复
热议问题