我正在尝试转换 Firebase Cloud Firestore 中具有数组的字段。该字段存储在文档中,并包含 10 个值。
我可以使用以下代码获取数据,但是我想知道是否可以将此数据转换为列表?
public void getAllowedPostcodes(){
DocumentReference docRef =
db.collection("AllowedPostcodes").document("tmGzpfFPFTwGw28uS8y1");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
我已经尝试了以下方法,但它无法编译:
"Cannot resolve constructor 'ArrayList(java.util.Map<java.lang.String,java.lang.Object>)"
这是我的代码:
List<String> allowedData = new ArrayList<String>(task.getResult().getData());
最佳答案
创建一个 forEach 循环来迭代每个字段,将其转换为 String 并将其添加到 ArrayList:
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
for(Object item : task.getResult().getData().values())
allowedData.add(item.toString());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
关于java - 将 Firebase 字段数组转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016643/