如何从 Firestore 获取数组? [英] How to get an array from 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 安卓:
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);
}
});
控制台输出如下:
{dungeon_group=[3P,紧急,任务挑战,降临,协作,日常,技术,正常]}
{dungeon_group=[3P, Urgent, Mission Challenge, Descended, Collaboration, Daily, Technical, Normal]}
推荐答案
当你调用 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");
- 类型转换中的语法错误
这篇关于如何从 Firestore 获取数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!