Reputation: 138
When I try to retrieve data from the database and save it into an array list I get the following error: com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap
@Override
public List<Player> getPlayers(String gameId) {
final List<Player> commentKeys = new ArrayList<>();
DatabaseReference nishi = FirebaseDatabase.getInstance().getReference("players");
Query query = nishi.orderByChild("game_id").equalTo(gameId);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot childSnapshot : snapshot.getChildren()) {
commentKeys.add((Player) childSnapshot.getValue());
}
Log.d("Data:", commentKeys.toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return commentKeys;
}
This is my Player
class:
public class Player {
private String playerId;
private String name;
private String color;
private int points;
private String gameId;
public Player() {
}
public Player(String id, String name, String color, int points, String gameId) {
this.playerId = id;
this.name = name;
this.color = color;
this.points = points;
this.gameId = gameId;
}
public String getPlayerId() {
return playerId;
}
public void setPlayerId(String playerId) {
this.playerId = playerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public String getGameId() {
return gameId;
}
public void setGameId(String gameId) {
this.gameId = gameId;
}
}
What am I doing wrong?
Upvotes: 0
Views: 2171
Reputation: 106
Try to clarify what kind of data gets your childSnapshot.getValue:
for (DataSnapshot childSnapshot : snapshot.getChildren()) {
commentKeys.add((Player) childSnapshot.getValue());
}
If it gets HashMap so you should change your:
final List<Player> commentKeys = new ArrayList<>();
I hope it will help.
Upvotes: 0
Reputation: 138824
This means that childSnapshot.getValue()
does not return an object of Player
class even if you are casting it to Player
. Because a Firebase database is structured as pairs of key and values, which means that every node of your Firebase database is a Map
, on that particular location you are not getting an object of Player
class, you are getting a java.util.HashMap
. It seems like you're simply reading the data at the wrong level in your JSON tree. The solution is to attach your listener on the correct level in the tree, which should be mapped exactly like your Player
class.
And don't forget to add the declation of your List<Player> commentKeys = new ArrayList<>();
inside the onDataChange()
method, otherwise it will always be null.
Upvotes: 2