在Android的Firestore中创建自定义文档ID,而不是生成随机的ID [英] Create a custom document id in firestore in android, instead of generating random one

查看:41
本文介绍了在Android的Firestore中创建自定义文档ID,而不是生成随机的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编辑此代码,以便可以在Firestore中创建自己的自定义文档ID?

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());
        }
    });

推荐答案

如果要创建使用CollectionReference的

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

使用指定的POJO作为内容向此集合添加一个新文档,并自动为其分配一个文档ID.

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

您应该使用DocumentReference的 set()方法:

You should use DocumentReference's set() method:

覆盖此DocumentRefere引用的文档

Overwrites the document referred to by this DocumentRefere

如果要获取生成的文档ID或在参考中使用自定义ID,请使用以下代码行:

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);

这篇关于在Android的Firestore中创建自定义文档ID,而不是生成随机的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆