How to Convert Firebase data to Java Object…?

后端 未结 5 1040
独厮守ぢ
独厮守ぢ 2020-11-27 12:12

Using Firebase Library to send data to the server in the form Message(String, String) added to the HashMap

Exampl

5条回答
  •  春和景丽
    2020-11-27 12:30

    There are two more way to get your data out of the Firebase DataSnapshot that don't require using a Map.

    First appoach is to use the methods of DataSnapshot to traverse the children:

    ref = new Firebase("https://my.firebaseio.com/messages").limitToLast(10);
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
                String name = (String) messageSnapshot.child("name").getValue();
                String message = (String) messageSnapshot.child("message").getValue();
            }
        }
    
        @Override
        public void onCancelled(FirebaseError firebaseError) { }
    });
    

    In the above snippet we use getChildren() to get an Iterable of your messages. Then we use child("name") to get each specific child property.

    The second approach is to use the built-in JSON-to-POJO serializer/deserializer. When you're sending the message list, the Message objects inside it are serialized to JSON and stored in Firebase.

    To get them out of it again, you have to do the inverse:

    ref = new Firebase("https://my.firebaseio.com/messages").limitToLast(10);
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
                Message message = messageSnapshot.getValue(Message.class);
            }
        }
    
        @Override
        public void onCancelled(FirebaseError firebaseError) { }
    });
    

    In this second snippet, we're still using getChildren() to get at the messages, but now we deserialize them from JSON straight back into a Message object.

    For a simple sample application using that last approach, have a look at Firebase's AndroidChat sample. It also shows how to efficiently deal with the list of messages (hint: FirebaseListAdapter).

提交回复
热议问题