首页 > 解决方案 > 如何更新 Firestore 文档哪些字段是字符串和整数的混合?

问题描述

我有一个这样的 Firestore 集合:

在此处输入图像描述

假设我想通过更改其地址成本值来更新文档“S4vfct....”。这是我的代码:

FirebaseFirestore firestore = FirebaseFirestore.getInstance();
final CollectionReference colRef = firestore.collection("kontrakan);

colRef.whereEqualTo("owner", OWNER_NAME).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {

            for (QueryDocumentSnapshot document : task.getResult()) {
                Map<Object, String> map = new HashMap<>();
                map.put("address", edtAddress.getText().toString());
                map.put("cost", edtCost.getText().toString());
                colRef.document(document.getId()).set(map, SetOptions.merge());
                Toast.makeText(getApplicationContext(), “Detail has been successfully updated.”, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), “Cannot update detail.”, Toast.LENGTH_SHORT).show();
        }
    }
});

代码成功更新了address的值,因为它是一个字符串。但不会改变cost,因为它是一个 int 。如何解决这个问题?

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


代码成功地更新了地址的值,因为它是一个字符串。但不会改变成本,因为它是一个整数。如何解决这个问题?

这是因为在以下代码行中:

map.put("cost", edtCost.getText().toString());

您正在尝试使用字符串值更新“成本”属性,而数据库中的“成本”属性是一个数字。为了解决这个问题,请将上面的代码行更改为:

map.put("cost", Long.parseLong(edtCost.getText().toString()));

推荐阅读