I'm quite new to cloud Firestore but I'm trying to learn it to my best.
Can someone please explain how could I add an object (with nested fields) in a document and then retrieve/get it back?
I know how to add data (such as String) through Hashmap
and add()
method and get it back using get()
method but I have no idea about Objects.
Any help would be appreciated.
Thanks!
EDIT: I studied the android developer docs and found solution to add objects with nested fields in it. but now I'm struggling with how to retrieve them. I tried the following code:
DocumentReference docRef =
db.collection("Users").document("myDocument");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>({
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
Object object = task.getResult().getData().get("myObject");
String str = object.toString();
tv.setText(str);
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
it's showing the objects's value not the nested fields' value within the object. How can i get the field values of the object? By the way, I checked the following post Accessing data stored as object in firestore and tried it's answer but my app gets crashed with the following log error:
" java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object java.util.HashMap.get(java.lang.Object)' on a null object
reference
Any opinion/help would be much appreciated! "