gpt4 book ai didi

java - 在 Firebase android 中写入数组

转载 作者:搜寻专家 更新时间:2023-10-30 21:17:39 24 4
gpt4 key购买 nike

我正在尝试将其写入我的 Firebase

parent

--0 : 约翰

--1 : 蒂姆

--2 : 山姆

--3 : 本

我在做这个

String[] names = {"John","Tim","Sam","Ben"};
myFirebaseRef.setValue(names);

它没有写任何东西。

它适用于 Firebase 的 Chrome 控制台。

这不是将数组写入 firebase 的方式吗?

谢谢

最佳答案

.setValue() 方法需要一个 List 而不是 Array

The native types accepted by this method for the value correspond to the JSON types: Boolean, Long, Double, Map, String, Object, List, Object...

Firebase ref = new Firebase("<my-firebase-app>/names"):
String[] names = {"John","Tim","Sam","Ben"};
List nameList = new ArrayList<String>(Arrays.asList(names));
// Now set value with new nameList
ref.setValue(nameList);

但是,我建议使用 Map 而不是 List。您可以使用名称作为键,而不是使用基于索引的键 (1,2,3...),以便更容易检索。

Firebase ref = new Firebase("<my-firebase-app>/names"):
HashMap<String, String> names = new HashMap()<String, String>;
names.put("John", "John");
names.put("Tim", "Tim");
names.put("Sam", "Sam");
names.put("Ben", "Ben");
ref.setValue(names);

现在如果您想检索数据,您只需要知道名称即可。

Firebase ref = new Firebase("<my-firebase-app>/names"):
Firebase johnRef = ref.child("john");
johnRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.value); // the String "John"
}
@Override
public void onCancelled(FirebaseError firebaseError) {

}
});

Read the Firebase docs for more information.

关于java - 在 Firebase android 中写入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34110853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com