Create a custom document id in firestore in androi

2019-08-27 04:24发布

How can I edit this code so I can create my own custom document id in Firestore?

users.add(new Accounts(fname, lname, uname, email, pass)).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
        @Override
        public void onSuccess(DocumentReference documentReference) {
            Toast.makeText(CreateAccount.this, "Data saved to FireStore", Toast.LENGTH_SHORT).show();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
             Log.d(TAG, e.toString());
        }
    });

1条回答
三岁会撩人
2楼-- · 2019-08-27 05:10

If you want to create a custom document id insead of the one that is generated when using CollectionReference's add() method which:

Adds a new document to this collection with the specified POJO as contents, assigning it a document ID automatically.

You should use DocumentReference's set() method:

Overwrites the document referred to by this DocumentRefere

If you want to get the document id that is generated or use a custom id in your reference, then please use following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
//String id = usersRef.collection("users").document().getId(); //Gets de generated id
String id = "yourCustomId";
Accounts accounts = new Accounts(fname, lname, uname, email, pass);
usersRef.document(id).set(accounts);
查看更多
登录 后发表回答