在Firebase Android中编写数组 [英] Writing array in Firebase android

查看:51
本文介绍了在Firebase Android中编写数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此内容写入Firebase

I am trying to write this to my Firebase

父母

-0:约翰

-1:蒂姆

-2:山姆

-3:本

我正在这样做

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

它什么也没写.

它可以在Chrome Console for Firebase上使用.

It works using the Chrome Console for Firebase.

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

Isn't this the way you write an array to firebase?

谢谢

推荐答案

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

该方法接受的本机类型对应于 JSON类型:布尔,长整型,双精度,映射,字符串,对象,列表,对象...

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 ...),这样更易​​于检索.

But, I recommend using a Map instead of a List. Rather than having an index based key (1,2,3...), you could use the name as the key so it's easier to retrieve.

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);

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

And now if you want to retrieve the data, you just need to know the name.

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) {

    }
});

阅读Firebase文档以获取更多信息.

这篇关于在Firebase Android中编写数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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