I\'m trying to extract the auto-generated Id under a document so I can use it elsewhere.
Here is the full code:
mStartChatButton.setOnClickListener(new V
1) The line of code I'm using to extract the document Id is not working and is extracting some other new auto-generated id (I'm guessing it is because I'm using the .document() method before the .getId() method).
No, this is happening because you are calling CollectionReference's document() method twice:
Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.
So every time you are calling document()
method, a fresh new id is generated. To solve this, please change the following lines of code:
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().set(myChatFields)
.addOnSuccessListener(/* ... */);
to
String id = mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().getId();
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document(id).set(myChatFields)
.addOnSuccessListener(/* ... */);
See, I have used the id
that was generated first time inside the refernce. Now inside the onSuccess()
method, you should use the same id
that was generated above:
myChatFields.put("chatCardId", id);
And not a newer one, as you do in your actual code.
2) Also the information for some reason does not get added to the HashMap with the last line of code I put.
This is happening becase you are using a wrong reference. Using a reference that contains the correct id
will solve your problem.