Firestore 查询 - 检查用户名是否已存在 [英] Firestore query - checking if username already exists

查看:15
本文介绍了Firestore 查询 - 检查用户名是否已存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关 Firestore 查询的帮助.我有一个 all_users 数据集合,包含每个用户信息的用户 ID 文档.firestore 数据库图像 我想检查用户名是否已经存在.我知道如何获取()文档并按照他们网页上的演示进行比较,但是数据查询呢?,这是我的代码

I need help with Firestore queries. I have a all_users data collection, user id-documents with each user information. firestore database image i want to check if username already exists. i get how to get() documents and compare as demonstrated on their webpage but what about data query?, this is my code

更新小部件 - (如果 mUser 文本字段和当前用户名不同)

updating the widgets - (if mUser text field and current username is not same)

 private void saveProfileSettings(){
    final String username = mUsername.getText().toString();
    //Case 1: user did not change their username
    if (!mUsers.getUsername().equals(username)){

        checkingIfusernameExist(username);

    }else {

    }
}

检查IfusernameExist方法

checkingIfusernameExist method

    private void checkingIfusernameExist(final String username){
    Log.d(TAG, "checkingIfusernameExist: Checking if " + username + " Exists");

    Query mQuery = mFirebaseFirestore.collection("all_users")
            .orderBy(getString(R.string.fields_username))
            .whereEqualTo("username", username);

    mQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

            if (documentSnapshots != null){
                Log.d(TAG, "onEvent: username does not exists");
                Toast.makeText(getActivity(), "Username is available", Toast.LENGTH_SHORT).show();
            }
            for (DocumentSnapshot ds: documentSnapshots){
                if (ds.exists()){
                    Log.d(TAG, "checkingIfusernameExist: FOUND A MATCH: " + ds.toObject(Users.class).getUsername());
                    Toast.makeText(getActivity(), "That username already exists.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
 }

我没有收到任何错误,结果也没有.我到处搜索,但没有看到我的问题.另外,我可以处理的查询并不多.任何更正将不胜感激,提前致谢.

I don't get any errors neither do results. I have searched everywhere and I haven't seen issues as mine. Plus there aren't much queries around i can work with. any correction would be appreciated, thanks in advance.

更新:经过几天的搜索,我实际上在下面得到的答案的帮助下想出了一个解决方案.因此,由于 firestore 没有操作逻辑,并且您希望在 .whereEqualTo 中不存在 username 时进行更新,请使用该任务查找包含任何有效负载.

UPDATE : after days of searching i actually came up with a solution with the help of answers i got below. so, since firestore does not not have an operational logic, and you want to update if username does not exists with the .whereEqualTo, use the task to find contains any payload.

对我有用的代码

checkingIfUsernameExists 方法

checkingIfUsernameExists method

private void checkingIfusernameExist(final String usernameToCompare){

    //----------------------------------------------------------------
    final Query mQuery = mFirebaseFirestore.collection("all_users").whereEqualTo("username", usernameToCompare);
    mQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            Log.d(TAG, "checkingIfusernameExist: checking if username exists");

            if (task.isSuccessful()){
                for (DocumentSnapshot ds: task.getResult()){
                    String userNames = ds.getString("username");
                        if (userNames.equals(usernameToCompare)) {
                            Log.d(TAG, "checkingIfusernameExist: FOUND A MATCH -username already exists");
                            Toast.makeText(getActivity(), "username already exists", Toast.LENGTH_SHORT).show();
                        }
                }
            }
            //checking if task contains any payload. if no, then update
            if (task.getResult().size() == 0){
                try{

                Log.d(TAG, "onComplete: MATCH NOT FOUND - username is available");
                Toast.makeText(getActivity(), "username changed", Toast.LENGTH_SHORT).show();
                //Updating new username............


                }catch (NullPointerException e){
                    Log.e(TAG, "NullPointerException: " + e.getMessage() );
                }
            }
        }
    });

推荐答案

要解决这个问题,请使用以下几行代码:

To solve this, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference allUsersRef = rootRef.collection("all_users");
Query userNameQuery = allUsersRef.whereEqualTo("username", "userNameToCompare");
userNameQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                if (document.exists()) {
                    String userName = document.getString("username");
                    Log.d(TAG, "username already exists");
                } else {
                    Log.d(TAG, "username does not exists");
                }
            }
        } else {
            Log.d("TAG", "Error getting documents: ", task.getException());
        }
    }
});

其中 userNameToCompare 是 String 类型,是要与之进行比较的用户的用户名.

In which userNameToCompare is of type String and is the user name of the user with which you want to make the comparison.

这篇关于Firestore 查询 - 检查用户名是否已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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