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

后端 未结 1 1352
独厮守ぢ
独厮守ぢ 2021-01-27 23:33

I know to get id:

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

But is mo

相关标签:
1条回答
  • 2021-01-27 23:44

    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);
                }
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题