将Firebase字段数组转换为列表 [英] Convert Firebase field array to list

查看:40
本文介绍了将Firebase字段数组转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换一个在Firebase Cloud Firestore中具有数组的字段.该字段存储在文档中,并且在该字段中包含10个值.

I'm trying to convert a field which has an array in Firebase Cloud Firestore. The field is stored in a document and contains 10 values in the field.

我可以使用以下代码获取数据,但是我想知道是否有可能将该数据转换为列表?

I can get the data using the following code however I would like to know if its possible to convert this data into a 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());
            }
        }
    });
}

但是我尝试了以下方法,但它没有编译为:

I have tried the following however, it doesn't compile saying:

"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:

Create a forEach loop to iterate through each field, cast it to String and add it to the 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());
                }
            }
        });

这篇关于将Firebase字段数组转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆