java – Firebase Firestore : How to convert document object to a POJO on Android-ThrowExceptions

Exception or error:

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());
            }
        });
How to solve:

With a DocumentSnapshot you can do:

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

###

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.

###

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.

Leave a Reply

Your email address will not be published. Required fields are marked *