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

Using the Realtime database, you can do the following:

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

as a way to map an object, how to do it using 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());
            }
        });
+6
source share
2 answers

With the help DocumentSnapshotyou can:

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

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

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

EDIT: Now I am using what is accepted on the accepted answer.

0
source

All Articles