How to retrieve custom object from cloud firestore? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to retrieve custom object from cloud firestore? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to adapt my realtime database to cloud firestore for a chat app. The object being stored is of class Message, which I created. I would like messages to be the document.

My RecyclerView adapter would retrieve them like this using realtime database:

public ChatRecyclerViewAdapter(Context mContext, ArrayList<String> mMessage, ArrayList<String> mAuthor, String mRoomID,DatabaseReference reference) {

    this.mContext = mContext;
    this.mRoomID = mRoomID;

    mDatabaseReference = reference.child(mRoomID+"_messages");
    recentMessages = mDatabaseReference.orderByKey().limitToLast(numberOfRecentMessages);
    recentMessages.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            // Convert data snapshot from Database into a Message Object

            Message message = dataSnapshot.getValue(Message.class);

            // Add it to an arrayList of Messages
            messageList.add(message);

            // Notice Changes
            notifyItemInserted(messageList.size());
        }

Below is how I’ve started to recreate this with Firestore. How do I convert the snapshot back into a Message in the Snapshot Listener’s onEvent method?

public ChatRecyclerViewAdapter(Context mContext, ArrayList<String> mMessage, ArrayList<String> mAuthor, String mRoomID, FirebaseFirestore firestore, CollectionReference reference) {
    this.mContext = mContext;
    this.mRoomID = mRoomID;

        messageList = new ArrayList<>();
        firestore = FirebaseFirestore.getInstance();
        mCollection = firestore.collection(mRoomID + "_messages");
        mCollection.addSnapshotListener(new com.google.firebase.firestore.EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
                for (DocumentChange documentChange:queryDocumentSnapshots.getDocumentChanges()){
                    switch (documentChange.getType()){
                        case ADDED:
                    }
                }
            }
        });
        mCollection.get();

Answer

In order to convert your document to class use:-

Message message = documentSnapshot.toObject(Message.class);

As explained here:-

DocumentReference docRef = db.collection("cities").document("BJ");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        City city = documentSnapshot.toObject(City.class);
    }
});

Update:- You can use this in your code as:-

firestore = FirebaseFirestore.getInstance(); 
firestore.collection(mRoomID + "_messages")
    .addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot snapshots,
                            @Nullable FirebaseFirestoreException e) { 
                for (DocumentChange dc : snapshots.getDocumentChanges()) {
                switch (dc.getType()) {
                    case ADDED:
                            Message message = snapshots.toObject(Message.class);
                        break;     
                }
            }
            }
        });
We are here to answer your question about How to retrieve custom object from cloud firestore? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji