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

查看:89
本文介绍了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 {

    }
}

checkingIfusernameExist方法

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不存在用户名的情况下进行更新,因此请使用该任务查找包含任何有效负载的内容.

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天全站免登陆