Retrieving Document Id from Firestore Collection (Android)

后端 未结 3 648
攒了一身酷
攒了一身酷 2021-01-25 08:04

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         


        
3条回答
  •  粉色の甜心
    2021-01-25 08:28

    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.

提交回复
热议问题