有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java对于DocumentSnapshot类型,foreach不适用于类型的错误意味着什么?

我正在按照this教程从firestore中的数组填充列表。但是我得到一个错误,foreach不适用于类型“DataSnapshot”

我严格遵循了教程,不确定是什么导致了这个错误

以下是我所拥有的:

private void readData(final MyCallback callback){
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()){
                        String group = document.getString("following");
                        followingList.add(group);
                    }
                    callback.onCallback(followingList);
                } else {
                }
            }
        });
    }

 private interface MyCallback {
     void onCallback(List<String> list);
 }

我应该能够使用此方法填写列表,但它没有编译错误:

error: for-each not applicable to expression type
required: array or java.lang.Iterable
found:    DocumentSnapshot

共 (3) 个答案

  1. # 1 楼答案

    task.getResult()将返回DocumentSnapshot类型的对象,该对象上没有符合Iterable接口的foreach方法。如果只获取一个文档,那么就不会有多个文档需要迭代。只需删除for循环并直接访问文档的字段:

    DocumentSnapshot document = task.getResult();
    String group = document.getString("following");
    followingList.add(group);
    

    如果您执行的查询可能会返回多个文档,那么您将只需要迭代文档,而这里没有这样做get()最多只返回一个文档

  2. # 2 楼答案

    我猜你的任务还没有完成。在Android开发者文档中,它描述了:

    Returns  TResult    
    Throws IllegalStateException    if the Task is not yet complete
    

    如您所见,异常不能用于每个

  3. # 3 楼答案

    根据https://firebase.google.com/docs/firestore/query-data/get-data,您可以使用QuerySnapshot

    db.collection("cities")
        .whereEqualTo("capital", true)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {   // LOOP
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });