I have created a user with the following code, however since the Document ID of the user is randomly generated, I would like to store the DocumentReference in a variable after it has been created. How could I do this?
FirebaseFirestore db = FirebaseFirestore.getInstance();
// Create a new user with a first, middle, and last name
Map<String, Object> user = new HashMap<>();
user.put("username", "username");
user.put("first", "Firstname");
user.put("last", "Lastname");
user.put("born", 1990);
// Add a new document with a generated ID
db.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
return null;
}
});
Since add() is asynchronous and returns immediately, you should expect to do anything with the resulting DocumentReference via the success listener you provided. Attempting to assign something to a local variable will not likely be helpful, because the rest of the code your method that invoked add() will almost certainly be complete by the time the callback is invoked.
Since you are creating the document under users folder, your document reference should be combination of user folder and document id