Lilian Sorlanski
Lilian Sorlanski

Reputation: 435

How to get the id when call add in one step in Firestore?

I know to get id:

String cityId = db.collection("cities").document().getId();
db.collection("cities").document(cityId).set(city);

But is more easy:

db.collection("cities").add(city);

But how to get id? It not work .add(city).getId(). No information in docs.

Upvotes: 0

Views: 237

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138869

How to get the id when call add in one step in Firestore?

There is no way in which you can get the document id in a single step, as you do when using a document() call. To solve this, you should add a complete listener. Try this:

db.collection("cities").add(city).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
    @Override
    public void onComplete(@NonNull Task<DocumentReference> task) {
        if (task.isSuccessful()) {
            DocumentReference document = task.getResult();
            if (document != null) {
                String id = document.getId(); //Do what you need to do with the document id
                Log.d(TAG, id);
            }
        }
    }
});

Upvotes: 1

Related Questions