保存和读取整数 Firestore Android
Posted
技术标签:
【中文标题】保存和读取整数 Firestore Android【英文标题】:Save and Read Integer Firestore Android 【发布时间】:2018-03-25 21:48:45 【问题描述】:我正在尝试为我的 android 游戏创建一个简单的 Stats 活动。我正在使用新的 Firestore 数据库。我已经能够将一个包含总分、最近得分、平均得分、总游戏数和高分的文档保存到我的 Firestore 数据库中,但是当我尝试从数据库中读取数据时,它返回一个空值。
public void readFromDB()
statsDoc.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>()
@Override
public void onSuccess(DocumentSnapshot documentSnapshot)
if(documentSnapshot.exists())
UserData userdata = documentSnapshot.toObject(UserData.class);
我的用户数据类:
/* 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;
当我用字符串测试它时它工作正常,但由于某种原因整数不起作用。提前致谢!
【问题讨论】:
【参考方案1】:在做了一些测试后,我得出结论,我们必须将 Longs 转换为 Integers,因为这是我们从 firestore 获取“Number”得到的。 这是我的数据的样子: 单击字段末尾的“编辑”图标,确保您存储了“数字”: 使用它来进行强制转换:Safely casting long to int in Java 我的代码如下所示:
int money = snapshot.getLong("money").intValue();
随时要求进一步解释!
【讨论】:
我觉得不错。如果没有提供字段,我建议先进行 NOT NULL 检查。【参考方案2】:enter code here
浮动 TotalAmount = Float.parseFloat
(String.valueOf(ObjectsrequireNonNull(getSnapshots().getSnapshot(position).getLong("TotalAmount"))));
试试看...... 101 %%%%
【讨论】:
以上是关于保存和读取整数 Firestore Android的主要内容,如果未能解决你的问题,请参考以下文章
如何减少 Flutter App 中的 Firestore 读取?
无法从 Flutter Web 读取 Firestore 中的数据(适用于 iOS 和 android)
Android Google Firestore 通知用户应用 Firestore 中有新数据