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());
}
});
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With