Unable to .getKey() after .add() to Cloud Firestore

Viewed 1344

I am migrating from Firebase Realtime Database to Cloud Firestore. Previously, I would .push() under the Realtime Database, and I would get the key of the .push() as follows:

final String key = mBaseRef.child("ABC").push().getKey();

It does not appear this method is available under the new Cloud Firestore. I am trying as such:

mStoreBaseRef.collection("ABC").add(pollMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
    @Override
    public void onComplete(@NonNull Task<DocumentReference> task) {
        String key = String.valueOf(mStoreBaseRef.collection("ABC").document().getId());
        Log.v("KEY", key);
        Toast.makeText(getApplicationContext(),key,Toast.LENGTH_LONG).show();
    }
}

The log simply is not returning the key that was created.

3 Answers

A reference to the added document is returned as the result of the completion task. The document ID is available from it:

    mStoreBaseRef.collection("ABC").add(pollMap)
            .addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
        @Override
        public void onComplete(@NonNull Task<DocumentReference> task) {
            if (task.isSuccessful()) {
                DocumentReference docRef = task.getResult();
                String key = docRef.getId();
                Log.v("KEY", key);
                Toast.makeText(getApplicationContext(), key, Toast.LENGTH_LONG).show();
            }
        }
    });

You can replace

final String key = mBaseRef.child("ABC").push().getKey();

with

DocumentReference key = db.collection("ABC").document();

This will return the auto-generated ID. You can then reference it later as:

key.set(data);

Or you can get the Firebase push ID as:

key.getId();

You can first get the Id by this code

 db = FirebaseFirestore.getInstance();
 String documentId=db.collection("MyCollection").document().getId();

and when you want to to set value for this document

db.collection("MyCollection").document(documentId).set(myDataObject);
Related