【问题标题】:How to update a Firestore document which fields are a mix of strings and ints?如何更新 Firestore 文档哪些字段是字符串和整数的混合?
【发布时间】:2020-10-19 08:11:31
【问题描述】:

我有一个这样的 Firestore 集合:

假设我想通过更改文档“S4vfct....”的 address 和 cost 值来更新它。这是我的代码:

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。如何解决这个问题?

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

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

    那是因为在下面的代码行中:

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

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

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

    【讨论】:

    • 这甚至不能编译,因为 map 是Map&lt;Object, String&gt; 的一个实例。嗯……
    • 在这种情况下,您可能会考虑使用两个对象进行更新,一个是Map&lt;Object, String&gt;,另一个是Map&lt;Object, Long&gt;,或者使用此post 中所述的多个更新。试一试,告诉我它是否有效。
    猜你喜欢
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    相关资源
    最近更新 更多