How to Convert Firebase data to Java Object…?

后端 未结 5 973
独厮守ぢ
独厮守ぢ 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:22

    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"));
    }
    
    0 讨论(0)
  • 2020-11-27 12:22

    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);
    
    0 讨论(0)
  • 2020-11-27 12:23

    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");
                        }
                    }
    
    0 讨论(0)
  • 2020-11-27 12:28

    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

    0 讨论(0)
  • 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<String, Object>.

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

    0 讨论(0)
提交回复
热议问题