我正在关注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
最佳答案
根据 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());
}
}
});
关于java - 对于 DocumentSnapshot 类型,错误 foreach 不适用于类型意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56844332/