java—从firebase读取数据并将其保存在数组列表中

tkclm6bt  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(369)

当我尝试从数据库检索数据并将其保存到数组列表中时,出现以下错误: com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap ```
@Override
public List getPlayers(String gameId) {
final List 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;
}
这是我的 `Player` 班级:

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;
}

}

我做错什么了?
olmpazwi

olmpazwi1#

这意味着 childSnapshot.getValue() 不返回 Player 上课,即使你是投给 Player . 因为firebase数据库的结构是成对的键和值,这意味着firebase数据库的每个节点都是一个 Map ,在那个特定的位置,你不会得到一个对象 Player 同学们,你们得到了一个 java.util.HashMap . 看起来您只是在json树中读取错误级别的数据。解决方案是将侦听器附加到树中的正确级别上,该级别应该与 Player 班级。
别忘了加上 List<Player> commentKeys = new ArrayList<>(); 内部 onDataChange() 方法,否则它将始终为空。

gywdnpxw

gywdnpxw2#

尝试澄清什么样的数据可以获取childsnapshot.getvalue:

for (DataSnapshot childSnapshot : snapshot.getChildren()) {
     commentKeys.add((Player) childSnapshot.getValue());
 }

如果它得到hashmap,那么您应该更改:

final List<Player> commentKeys = new ArrayList<>();

我希望这会有帮助。

相关问题