Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore : How to convert document object to a POJO on Android

With the Realtime Database, one could do this :

MyPojo pojo  = dataSnapshot.getValue(MyPojo.Class);

as a way to map the object, how does one do this with Firestore?

CODE :

FirebaseFirestore db = FirebaseFirestore.getInstance();
        db.collection("app/users/" + uid).document("notifications").get().addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document != null) {
                    NotifPojo notifPojo = document....// here
                    return;
                }

            } else {
                Log.d("FragNotif", "get failed with ", task.getException());
            }
        });
like image 354
Relm Avatar asked Oct 09 '17 05:10

Relm


People also ask

Can firestore store objects?

Cloud Firestore is optimized for storing large collections of small documents. All documents must be stored in collections. Documents can contain subcollections and nested objects, both of which can include primitive fields like strings or complex objects like lists.


3 Answers

With a DocumentSnapshot you can do:

DocumentSnapshot document = future.get();
if (document.exists()) {
    // convert document to POJO
    NotifPojo notifPojo = document.toObject(NotifPojo.class);
}
like image 112
Gabriele Mariotti Avatar answered Oct 07 '22 21:10

Gabriele Mariotti


Java

    DocumentSnapshot document = future.get();
if (document.exists()) {
    // convert document to POJO
    NotifPojo notifPojo = document.toObject(NotifPojo.class);
} 

Kotlin

 val document = future.get()
 if (document.exists()) {
    // convert document to POJO
     val notifPojo = document.toObject(NotifPojo::class.java)
  }

It is important to remember that you must provide a default constructor or you will get the classic deserialization error. For Java a Notif() {} should suffice. For Kotlin initialize your properties.

like image 6
Joel Avatar answered Oct 07 '22 21:10

Joel


Not sure if this is the best way to do it, but this is what I have so far.

NotifPojo notifPojo = new Gson().fromJson(document.getData().toString(), NotifPojo.class);

EDIT : i'm now using what's on the accepted answer.

like image 1
Relm Avatar answered Oct 07 '22 21:10

Relm