I am using firebase to retrieve data from database n use
Map
to get values, but it
Due to the way that Java implements generics (type-erasure), it is necessary to use a slightly more complicated method to properly resolve types for generic collections at runtime. To solve this problem, Firebase Database accepts subclasses of this class in calls to getValue (getValue(GenericTypeIndicator), getValue(GenericTypeIndicator)) and returns a properly-typed generic collection.
As an example, you might do something like this to get a list of Message instances from a DataSnapshot:
class Message {
private String author;
private String text;
private Message() {}
public Message(String author, String text) {
this.author = author;
this.text = text;
}
public String getAuthor() {
return author;
}
public String getText() {
return text;
}
}
// Later ...
GenericTypeIndicator<List<Message>> t = new GenericTypeIndicator<List<Message>>() {};
List<Message> messages = snapshot.getValue(t);
You need to use the getCheldrin
as follows
for (DataSnapshot snapshotNode: dataSnapshot.getChildren()) {
map.put(snapshotNode.getKey(), snapshotNode.getValue(YOUR_CLASS_TYPE.class));
}
Replace the YOUR_CLASS_TYPE
with the class type you expecting. notice that this class must have an empty constructor.
The error points out correctly where you are going wrong
Map<String, String> map = dataSnapshot.getValue(Map.class);
Map class uses parameter to define the types of Key and Object where as you don't give them and simply use Map.class
which fails.
Try the below code - since Key are always string and we can have any type of Object for them
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
Chage
Map<String, String> map = (Map<String,String>)dataSnapshot.getValue(Map.class);
by this
Map map = (Map) dataSnapshot.getValue(Map.class);
I had the same problem and solved it by handling the Object instead trying to have Firebase cast it.
Map <String, String> map = (Map)dataSnapshot.getValue();
did it for me.
To introduce the GenericTypeIndicator
, you can change this line:
Map<String, String> map = dataSnapshot.getValue(Map.class);
in to this:
GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
Map<String, String> map = dataSnapshot.getValue(genericTypeIndicator );
This should work well in your case. Please give it a try and let me know.