如何在事务Firestore之后读取对象?

时间:2018-03-26 11:31:12

标签: android firebase transactions google-cloud-firestore

如何在事务Firestore之后读取对象“数据”?为什么为快照创建此对象?如何将快照直接复制到文档或如何读取对象“数据”?

enter image description here

事务:

mFirestoreRef = mFirestore.collection("item_decor").document(item_holly_id);
builder.setView(v)
    .setTitle("Добавить элемент")
    .setPositiveButton("Добавить", (dialog, which) ->
        mFirestore.runTransaction((Transaction.Function<Void>) transaction -> {
            DocumentSnapshot snapshot = transaction.get(mFirestoreRef);

            long sumUpdateData = snapshot.getLong("sum");
            int sumUpdate = (Integer) sum.getSelectedItem();

            if(sumUpdateData >= sumUpdate) {
                transaction.update(mFirestoreRef, "sum", sumUpdateData - sumUpdate);
                DocumentReference addItemRef = mFirestore.collection("list_holly")
                    .document(holly.getSelectedItem().toString())
                    .collection("item_holly").document(snapshot.getId());

                    transaction.set(addItemRef, snapshot);
                    transaction.update(addItemRef, "sum", sumUpdate);
                }

读:

mFirestore.collection("list_holly").document(title.getTitle()).collection("item_holly")
    .get().addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                String name = document.getString("name"); // Does not work
            }
        } else {
    }
});

1 个答案:

答案 0 :(得分:1)

这是行不通的,因为你错过了一个属性。要解决此问题,请通过以下方式更改您的来电:

mFirestore.collection("list_holly")
    .document(title.getTitle())
    .collection("item_holly")
    .get().addOnCompleteListener(task -> {
        for (DocumentSnapshot document : task.getResult()) {
            Map<String, Object> data = (Map<String, Object>) document.get("data");
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                if (entry.getKey().equals("name")) {
                    String name = entry.getValue().toString();
                    Log.d("TAG", name);
                }
            }
        }
    });

输出结果为:Decor

data属性是Map,因此要实际获取名称,您只需要迭代Map。就是这样!