65

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

Example:

Firebase fb = new Firebase(URL);
Firebase msgRef = fb.child("finished");
HashMap<String, Message> msgList = new HashMap<>();
Message msg = new Message(m, n);
msgList.put(HASHKEY, msg);
msgRef.push().setValue(msgList);

While receiving data with Firebase method addValueEventListener() getting String in this Form

{ key = finished, value = {
    -Js9Rn0uttjYIGdcv8I1={Moosa={message=email, name=Kamran}},
    -Js9Vsmv6BnVzOzpl2L8={Moosa={message=msgs, name=Imran}}, 
    -Js9WtQ8yeDwVxQMFCZb={Moosa={message=samsung, name=Samad}}, 
    -Js9RarxoJPKn4RO2HaM={Moosa={message=Message, name=Moosa}}, 
    -Js9b6f75lwwbsqQNJz0={Moosa={message=Qmobile, name=Bilal}}, 
    -Js9aDxt8TlgTGUccuxu={Moosa={message=last, name=Moosa}}} }

How can I convert it into Message Object.....????

Micho
  • 3,929
  • 13
  • 37
  • 40
Moosa Baloch
  • 1,175
  • 1
  • 13
  • 25

5 Answers5

126

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

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

ref = FirebaseDatabase.getInstance().getReference("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.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).

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 2
    In your second approach how is the firebase data mapped to the properties of the pojo? Does the pojo property name and the firebase node name exactly needs to match with each other? – Parag Kadam Jun 29 '16 at 18:44
  • 2
    @ParagKadam yes, as long they have same field names. – Moses Aprico Oct 13 '16 at 17:47
  • 1
    What if the attributes like "name" and "message" are dynamic. how to get data snapshot and generate a object. Convert Json Object into Java object direcly. – Dushyant Suthar Nov 12 '16 at 07:01
  • 1
    You could get the values into a `Map`. But I recommend against that. If the objects are dynamic, you're better off sticking to the `DataSnapshot` itself. – Frank van Puffelen Nov 12 '16 at 16:36
11

So if you wanna get the messages you can do the following:

        for (DataSnapshot child : dataSnapshot.getChildren()){
    //child is each element in the finished list
    Map<String, Object> message = (Map<String, Object>)child.getValue();
    Message msg = new Message((String) message.getValue().get("message"),
            (String) message.get("name"));
}
M090009
  • 1,129
  • 11
  • 20
  • Its returning the null value in both conditions... dataSnapshot.getValue(); child.getValue(); – Moosa Baloch Jun 19 '15 at 09:44
  • can you show the request your send to firebase??also what method are you using to retrive the data `onDataChange` or `onChildAdded`?? – M090009 Jun 19 '15 at 09:49
  • `Firebase msgRef = fb.child("messagebox"); HashMap msgList = new HashMap<>(); Message msg = new Message(m, n); msgList.put("Moosa", msg); msgRef.push().setValue(msgList);` – Moosa Baloch Jun 19 '15 at 09:56
  • ok can you check the `dataSnapshot` and the `child` values and print them – M090009 Jun 19 '15 at 10:00
  • DATASNAPSHOT ---> `{-Js9Rn0uttjYIGdcv8I1={Moosa={message=email, name=Kamran}}, -Js9Vsmv6BnVzOzpl2L8={Moosa={message=msgs, name=Imran}}, -Js9WtQ8yeDwVxQMFCZb={Moosa={message=samsung, name=Samad}}, -Js9RarxoJPKn4RO2HaM={Moosa={message=Message, name=Moosa}}, -Js9b6f75lwwbsqQNJz0={Moosa={message=Qmobile, name=Bilal}}, -Js9aDxt8TlgTGUccuxu={Moosa={message=last, name=Moosa}}}` – Moosa Baloch Jun 19 '15 at 10:04
  • Child Values- Iterating --> `{Moosa={message=Message, name=Moosa}} {Moosa={message=email, name=Kamran}} {Moosa={message=msgs, name=Imran}} {Moosa={message=samsung, name=Samad}} {Moosa={message=last, name=Moosa}} {Moosa={message=Qmobile, name=Bilal}}` – Moosa Baloch Jun 19 '15 at 10:05
  • so you got the children, the only thing here is just one more step let me update the answer – M090009 Jun 19 '15 at 10:11
  • 1
    got it using nested for loop and iterating the child values with the help of above solution.... Thnx Bro.... – Moosa Baloch Jun 19 '15 at 10:15
  • Well why did you add Moosa as a key for the messages?? because that what made you get the child as a map then get the message from the map which key is Moosa – M090009 Jun 19 '15 at 10:17
  • No Reason... It's my name... :) – Moosa Baloch Jun 19 '15 at 10:30
9

Iterating the values of dataSnapshot and getting Children using nested for loop to iterate the child elements of children and getting the Required Value...

for (DataSnapshot child : dataSnapshot.getChildren()) {
                    for (DataSnapshot single : child.getChildren()) {
                        Map<String, Object> map = (Map<String, Object>) single.getValue();
                        String a = (String) map.get("message");
                        String b = (String) map.get("name");
                        textView.append(b + " -- " + a + "\n");
                    }
                }
Moosa Baloch
  • 1,175
  • 1
  • 13
  • 25
6

Use this code if you want to convert firebase object to json using Gson Library :

databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Object object = dataSnapshot.getValue(Object.class);
            String json = new Gson().toJson(object);
            Example example= new Gson().fromJson(json, Example.class);
            Log.e("json","json: " + example.getGlossary());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

This will convert complete Database Structure to String json and then json to class object using Gson Lib

Alok Gupta
  • 1,806
  • 22
  • 21
2

You could make it using a ChildEventListener instead of a ValueEventListener.

For example. I have a class called match with 3 string properties {id, name, photoUrl} then I add all the values in a List. Instead of using a for loop it works for me with this code.

    Query queryRef = mDatabase.child("users").child(user.getUid()).child("matches");

    ChildEventListener listener = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
            Match match = dataSnapshot.getValue(Match.class);
            matchList.add(match);
            mAdapter = new MatchAdapter(getContext(), matchList);
            recyclerView.setAdapter(mAdapter);
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
            Log.d("MESSAGEFRAGMENT", "CHILDCHANGE");
        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };
    queryRef.addChildEventListener(listener);
Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
Sergio
  • 53
  • 6