本文介绍了如何从Firestore获取阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下所示的数据结构存储在Cloud Firestore中.我要保存dungeon_group,它是存储在Firestore中的字符串数组.

I have the data structure illustrated below stored in Cloud Firestore. I want to save the dungeon_group which is an array of strings stored in Firestore.

我很难获取数据并存储为数组.我只是能够得到一个奇怪的字符串,但是有什么方法可以存储为字符串数组呢?下面是我使用的代码.

I have difficulty in getting the data and stored as an array. I am just able to get a weird string but any method to store as a string array? Below is the code I used.

我可以按照以下方式在Swift中实现此目标,但不确定如何在Android中做到这一点.

I am able to achieve this in Swift as follow, but not sure how to do the same in Android.

迅速:

Firestore.firestore().collection("dungeon").document("room_en").getDocument { 
    (document, error) in
    if let document = document {
        let group_array = document["dungeon_group"] as? Array ?? [""]
        print(group_array)
    }    
}

Java Android:

Java Android:

FirebaseFirestore.getInstance().collection("dungeon")
                 .document("room_en").get()
                 .addOnCompleteListener(new 
                     OnCompleteListener<DocumentSnapshot>() {
                     @Override
                     public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                         DocumentSnapshot document = task.getResult();
                         String group_string= document.getData().toString();
                         String[] group_array = ????
                         Log.d("myTag", group_string);
                     }
                 });

控制台输出如下:

推荐答案

调用 DocumentSnapshot.getData(),它将返回一个Map.您只是在该地图上调用toString(),这将使您转储文档中的所有数据,但这并不是特别有用.您需要按名称访问dungeon_group字段:

When you call DocumentSnapshot.getData(), it returns a Map. You're just calling toString() on that map, which is going to give you a dump of all the data in the document, and that's not particularly helpful. You need to access the dungeon_group field by name:

DocumentSnapshot document = task.getResult();
List<String> group = (List<String>) document.get("dungeon_group");

  • 类型转换中的语法错误
    • edit:syntax error in typecasting
    • 这篇关于如何从Firestore获取阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 15:27