代码之家  ›  专栏  ›  技术社区  ›  Илья Литвинцев

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

  •  2
  • Илья Литвинцев  · 技术社区  · 7 年前

    如何在事务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 回复  |  直到 7 年前
        1
  •  2
  •   Alex Mamo    7 年前

    这不起作用,因为您缺少一个属性。要解决此问题,请使用以下内容更改get呼叫:

    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 ,所以要真正获得名称,只需迭代 地图 。就是这样!