【问题标题】:Firestore- checking if username already exists [duplicate]Firestore-检查用户名是否已经存在[重复]
【发布时间】:2018-10-17 18:26:37
【问题描述】:

我需要有关 Firestore 的帮助。我有一个 AllUsers 数据集合,包含每个用户信息的用户 ID 文档。我想检查用户名是否已经存在; // “那个用户名已经存在”。我该怎么做?

` setupBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final String user_name = setupName.getText().toString();

            Map<String, Object> commentsMap = new HashMap<>();
            commentsMap.put("user_id", user_id);
            commentsMap.put("timestamp", FieldValue.serverTimestamp());
            commentsMap.put("user_name",user_name);
            firebaseFirestore.collection("AllUsers").document(user_id).set(commentsMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        Intent asda=new Intent(getApplicationContext(),MainActivity.class);
                        startActivity(asda);
                        finish();
                   }

                }
            });

`

【问题讨论】:

  • 你得到了用户名,所以我想将用户名与数据库中保存的用户名进行比较并不难。顺便说一句,看起来重复。
  • 我做不到,请帮帮我。
  • 需要查看firebase firestore的结构。你也会添加结构吗?作为图像或其他东西。

标签: java android firebase google-cloud-firestore


【解决方案1】:

希望这会有所帮助。

setupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String userName = setupName.getText().toString();

                CollectionReference usersRef = firestore.collection("Users");
                Query query = usersRef.whereEqualTo("username", userName);
                query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if(task.isSuccessful()){
                            for(DocumentSnapshot documentSnapshot : task.getResult()){
                                String user = documentSnapshot.getString("username");

                                if(user.equals(userName)){
                                    Log.d(TAG, "User Exists");
                                    Toast.makeText(MainActivity.this, "Username exists", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }

                        if(task.getResult().size() == 0 ){
                            Log.d(TAG, "User not Exists");
                            //You can store new user information here

                        }
                    }
                });
            }
        });

【讨论】:

  • 拯救我的一天兄弟
  • 这是一个了不起的答案,完美运行。但是如果我还想检查电子邮件是否已经存在怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多