保存并读取Integer Firestore Android

Ste*_*son 8 java database android firebase google-cloud-firestore

我正在尝试为我的Android游戏创建一个简单的Stats活动.我正在使用新的Firestore数据库.我已经能够将文档保存到我的Firestore数据库中,包括总分,最近得分,平均得分,总游戏和高分,但是当我尝试从数据库中读回数据时,它返回null.

public void readFromDB(){
    statsDoc.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            if(documentSnapshot.exists()){
                UserData userdata = documentSnapshot.toObject(UserData.class);
            }
        }
Run Code Online (Sandbox Code Playgroud)

我的Userdata类:

/* Copyright statement */

package com.squidstudios.android.balloonpopper.utils;

import com.google.firebase.database.IgnoreExtraProperties;

/**
 * UserData.java
 *
 * This class represents a single user's data including username, email, number of points earned,
 * a saved state of their progress towards earning a single point, and their password.
 */
@IgnoreExtraProperties
public class UserData {
    public String email;
    public int total_points;

public int avg_score;
public int high_score;
public int total_games;
public int prev_score;

public UserData() {
    // Default constructor required for calls to DataSnapshot.getValue(UserData.class)
}


public int getTotal_games() {
    return total_games;
}

public void setTotal_games(int total_games) {
    this.total_games = total_games;
}

public int getTotal_points() {
    return total_points;
}

public void setTotal_points(int total_points) {
    this.total_points = total_points;
}

public int getAvg_score() {
    return avg_score;
}

public void setAvg_score(int avg_score) {
    this.avg_score = avg_score;
}

public int getHigh_score() {
    return high_score;
}

public void setHigh_score(int high_score) {
    this.high_score = high_score;
}


public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public int getPrev_score() {
    return prev_score;
}

public void setPrev_score(int prev_score) {
    this.prev_score = prev_score;
}

}
Run Code Online (Sandbox Code Playgroud)

当我用字符串测试它时它工作正常但由于某种原因整数不起作用.提前致谢!

Lui*_*lla 17

经过一些测试后,我得到了将Longs转换为Integers的结论,因为这是我们从firestore中获取"Number"所得到的.这是我的数据:
1]

确保通过单击字段末尾的"编辑"图标存储"数字":


使用它来进行转换:在Java中安全地将long转换为int

我的代码如下所示:

int money = snapshot.getLong("money").intValue();
Run Code Online (Sandbox Code Playgroud)


随意请求进一步解释!

  • 在我看来很好。对于未提供字段的情况,我建议先进行 NOT NULL 检查。 (2认同)