使用Firebase Java API检索/格式化数据的最佳方法 [英] Best way to retrieve/format data using Firebase Java API

查看:166
本文介绍了使用Firebase Java API检索/格式化数据的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firebase 用于 Android 项目上的数据存储,并使用 Firebase Java API 来处理数据。不过,我不确定我是否尽可能高效地完成了这项工作,并且希望获得有关检索和格式化数据的最佳做法的建议。我的 Firebase 版本库看起来像这样....

  -POLLS 
NUMPOLLS - 5
(pollskey) - NAME - Poll1
NUMELECTIONS - 2
选举
(electionkey) - NAME - Election1
NUMNOMINATIONS - 2
NUMVOTERS - 2
NUMBERTOELECT - 1
VOTERS - (votesrkey) - NAME - Charles
NUMBER - (678)333-4444



(votkey) - ...
提名 - (提名key) - 名字 - Richard Nixon
NUMBEROFVOTES - 2



(提名键) - ...



(electionskey) - ...



(pollskey) - ...

所以,例如这里我试图从投票中获取所有数据以列出投票姓名,选举名称以及每次选举的候选人姓名和投票数。在我的主要活动的 OnCreate()函数中获得POLLS级别 DataSnapshot ...

  private static final Firebase polls = pollsFirebase.child(Polls); 
protected void onCreate(Bundle savedInstanceState){

polls.addListenerForSingleValueEvent(new ValueEventListener(){
$ b @Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot child:snapshot.getChildren()){
if(!child.getName()。equals(NumPolls)){
createPollTableAndHeaders(child);
}
}

}
});

$ / code>

然后我继续读出我需要的单个数据 getValue() DataSnapshots 上,然后检查结果 HashMaps
pre $ private $ createPollTableAndHeaders(DataSnapshot poll){
String pollName =;
int numPolls;
Object p = poll.getValue();
if(p instanceof HashMap){
HashMap pollHash =(HashMap)p;
if(pollHash.containsKey(Name)){
pollName =(String)pollHash.get(Name);

if(pollHash.containsKey(Elections)){
HashMap election =(HashMap)pollHash.get(Elections);
Iterator electionIterator = election.values()。iterator();
while(electionIterator.hasNext()){
Object electionObj = electionIterator.next();
if(electionObj instanceof HashMap){
HashMap electionHash =(HashMap)electionObj;
if(electionHash.containsKey(Name)){
String electionName =(String)electionHash.get(Name);
}
}
};




$ b这似乎是一个非常繁琐的方法,数据结构,我想知道是否有更好的方法。


我已经在文档中看到了 getValue(java.lang.Class< T> valueType)但一直没有能够得到它在我的情况下工作,因为我正在使用组合的对象,而不仅仅是原始类型的容器。函数如何知道要将 Firebase 数据分配给模型对象的哪些成员变量?它是否与 Firebase 键名称与成员变量匹配,因此它们必须完全相同,区分大小写?那么如何处理 Firebase 生成的密钥名称,如推送到 List ?如何为构成对象构造模型对象? 与杰克逊对象映射库相同的规则(这是我们在内部使用的: http://wiki.fasterxml.com/JacksonInFiveMinutes ) 。所以,你的Java类必须有默认的构造函数(没有参数)和getters为你想要分配的属性( https://www.firebase.com/docs/java-api/javadoc/com/firebase/client/DataSnapshot.html#getValue(java.lang中。类))。
总之,是的,Firebase中的键名必须与成员变量匹配。

有关使用复合对象(包括列表)的示例,请参阅 AndroidDrawing 。具体而言, Segment 类包含一个 Point 实例的列表。有一个使用 .push()方法生成的数据列表。由于生成的键名称是字符串,因此它们可以在客户端是唯一的,所以它们反序列化 Map s而不是 List 秒。但是,如果你遍历 dataSnapshot.getChildren(),它们将按顺序返回。

另外,if你不想反序列化成一个HashMap,你可以在DataSnapshot上使用child()方法。例如:

 

字符串pollName = poll.child(Name)。getValue(String 。类);
DataSnapshot election = poll.child(Elections); (DataSnapshot选举:选举.getChildren()){
字符串选举名称=选举.child(名字)。getValue(String.class);






$ b

在这个例子中,任何不存在的值返回为 null



希望有帮助!


I'm using Firebase for data storage on an Android project, and using the Firebase Java API to deal with data. I'm not sure I'm doing it as efficiently as possible, though, and I'd like some advice on best practices for retrieving and formatting data. My Firebase repository looks something like this....

-POLLS
    NUMPOLLS - 5
    (pollskey) - NAME - Poll1
            NUMELECTIONS - 2
            ELECTIONS 
                (electionskey) - NAME - Election1
                        NUMNOMINATIONS - 2
                        NUMVOTERS - 2
                        NUMBERTOELECT - 1
                        VOTERS - (votesrkey) - NAME - Charles
                                         NUMBER - (678) 333-4444
                                 .
                                 .
                                 .
                                 (voterskey) - ...
                        NOMINATIONS - (nominationskey) - NAME - Richard Nixon
                                              NUMBEROFVOTES - 2
                                       .
                                       .
                                       .
                                      (nominationskey) - ...
            .
            .
            .
            (electionskey) - ...
     .
     .
     .
     (pollskey) - ...

So, for example here I'm trying to get all data out of a poll to list poll name, it's election names, and the candidate names and number of votes for each election. I get the POLLS level DataSnapshot during the OnCreate() function of my main activity like this...

private static final Firebase polls = pollsFirebase.child("Polls");
protected void onCreate(Bundle savedInstanceState) {

        polls.addListenerForSingleValueEvent(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot snapshot) {
                for (DataSnapshot child : snapshot.getChildren()) {
                    if (!child.getName().equals("NumPolls")) {
                        createPollTableAndHeaders(child);
                    }
                }

            }
        });
    }

Then I proceed to read out the individual pieces of data I need by successively calling getValue() on DataSnapshots, and checking the keys of the resulting HashMaps...

private void createPollTableAndHeaders(DataSnapshot poll) {
    String pollName = "";
    int numPolls;
    Object p = poll.getValue();
    if (p instanceof HashMap) {
        HashMap pollHash = (HashMap) p;
        if (pollHash.containsKey("Name")) {
            pollName = (String) pollHash.get("Name");
        } 
        if (pollHash.containsKey("Elections")) {
            HashMap election = (HashMap) pollHash.get("Elections");
            Iterator electionIterator = election.values().iterator();
            while (electionIterator.hasNext()) {
                Object electionObj = electionIterator.next();
                if (electionObj instanceof HashMap) {
                    HashMap electionHash = (HashMap) electionObj;
                    if (electionHash.containsKey("Name")) {
                        String electionName = (String) electionHash.get("Name");
                    }
                }
            };
        }
    }

This seems like a pretty tedious way to drill down through the data structure, and I'm wondering if there's a better way.

I've seen the getValue(java.lang.Class<T> valueType) method in the documentation, but haven't been able to get it to work in my case, since I'm working with composed objects and not just containers for primitive types. How does the function know what Firebase data to assign to which member variables of a model object? Does it match Firebase key names with member variables, and therefore do these have to be exactly the same, with case sensitivity? How would that deal with Firebase generated key names like produced when pushing to a List? How to you construct model objects for composed objects?

解决方案

The getValue(java.lang.Class valueType) method follows the same rules as the jackson object mapping library (it's what we use internally: http://wiki.fasterxml.com/JacksonInFiveMinutes). So, your Java classes must have default constructors (no arguments) and getters for the properties that you want assigned (https://www.firebase.com/docs/java-api/javadoc/com/firebase/client/DataSnapshot.html#getValue(java.lang.Class)). In short, yes, the key names in Firebase must match the member variables.

For an example using composite objects, including a list, see AndroidDrawing. Specifically, the Segment class contains a list of Point instances. There is one catch using lists of data generated with the .push() method. Since the key names generated are Strings so that they can be unique across clients, they deserialize the Maps rather than Lists. However, if you iterate over dataSnapshot.getChildren() they will be returned in order.

In addition, if you don't want to deserialize into a HashMap, you can use the child() method on DataSnapshot. For instance:


String pollName = poll.child("Name").getValue(String.class); 
DataSnapshot elections = poll.child("Elections");
for (DataSnapshot election : elections.getChildren()) {
    String electionName = election.child("Name").getValue(String.class);
}

In this example, any values that don't exist will be returned as null.

Hope that helps!

这篇关于使用Firebase Java API检索/格式化数据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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