1
votes

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! "

1

1 Answers

1
votes

document.getData() returns "almost" JSON data. This can be interpreted by using Gson and JsonElement. Example: if objectName refers to the name of object and Classname is the name of the class of desired object,

Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(document.getData());
Classname objectName = gson.fromJson(jsonElement, Classname.class);

The code can be shortened like this:

Gson gson = new Gson();
Classname objectName = gson.fromJson(gson.toJsonTree(document.getData()), Classname.class);

Incase you wanted a HashMap, you can cast it like this

HashMap<String, FieldValueClass> map = (HashMap<String, FieldValueClass>)(document.getData()).

But this works only when all fields can be cast to FieldValueClass.