将单个firestore firebase字段从字符串转换为int



我已经设法使用云firestore在firebase中存储数据

我已经创建了一个集合,可以存储用户的额外细节,如他们的年龄、身高和体重

我的应用程序中有一个功能,可以根据用户的体重计算用户每天的饮水率,计算结果是用户的体重除以30

所以当用户打开页面时,它会直接计算它

然而。存储在firestore中的数据类型被标识为String,并且我一直在尝试将数据字段类型转换为Int,以便程序能够执行。但是我得到了像

这样的错误

. lang。NumberFormatException:用于输入字符串:"com.google.firebase.firestore.DocumentReference@a4443fb">

public class drinkingWater extends BaseMainMenu {
TextView cRslt;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
String userID;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drinking_water);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cRslt = findViewById(R.id.result);
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
DocumentReference docRef = mStore.collection("userDetail").document(userID);
docRef.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
int n1 = Integer.valueOf(String.valueOf(mStore.collection("userDetail").document(userID + "Weight")));
int n2 = 30;
int sum = n1 / n2;
cRslt.setText(String.valueOf(sum));

}
});
}
}

如果我正确地阅读了您的代码,您在文档中有一个Weight字段,并且您希望获得该字段的值。您可以使用以下命令从DocumentSnapshot对象获取数据:

documentSnapshot.get("Weight)

如果Weight存储为整数值,则为:

int n1 = documentSnapshot.get("Weight)

如果Weight被存储为int值的字符串表示形式,它将是:

int n1 = Integer.valueOf(documentSnapshot.get("Weight));

错误提示不能将类型为text的字符串转换为直接整数。如果字符串包含任何文本,则不能将其转换为数字。我看到你也是parsing UserId,"userDetailInteger,这是不可能的。首先,在另一个变量中取出字符串中的所有文本,然后可以轻松地将包含weight的变量从字符串转换为整数。确保你的weight变量只有数字格式。

最新更新