将Firebase字段数组转换为列表

时间:2018-02-27 19:38:22

标签: java android firebase google-cloud-firestore

我尝试在Firebase Cloud Firestore中转换具有阵列的字段。该字段存储在文档中,并在字段中包含10个值。

我可以使用以下代码获取数据但是我想知道是否可以将此数据转换为List?

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());

数据库结构如下: enter image description here

1 个答案:

答案 0 :(得分:1)

创建一个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());
                }
            }
        });