将Firebase字段数组转换为列表

问题描述 投票:0回答:1

我正在尝试转换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

java android firebase google-cloud-firestore
1个回答
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());
                }
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.