简体   繁体   English

通过数据库查询用户名以确保当用户想要更改其现有用户名时不存在相同的用户名

[英]Querying usernames through database to make sure identical one doesn't exist when user wants to change their existing username

What I am trying to do is when a user decides to edit their username I would like to run a query through the database making sure that that username which they pick hasn't been taken.我想做的是当用户决定编辑他们的用户名时,我想通过数据库运行查询,确保他们选择的用户名没有被使用。 For the most part, I think I have it right, I run a for loop to look through all of the usernames that have been added to the database, and if one matches it shows A Toast message.在大多数情况下,我认为我是对的,我运行一个 for 循环来查看已添加到数据库中的所有用户名,如果匹配,则显示Toast消息。

The issue is it shows the Toast message, but still changes the username even if it's in use.问题是它显示了Toast消息,但即使用户名正在使用,它仍然会更改用户名。 I know it's simple code, but I can't figure out what I am doing wrong.我知道这是简单的代码,但我不知道我做错了什么。 Someone mind having a look?有人介意看看吗? I think the issue is the mUsername , because I set it in the updateProfile();我认为问题是mUsername ,因为我在updateProfile();中设置了它。 method, but if I set the new mUserName1 , well I can't because it's an EditText and not a String .方法,但是如果我设置了新的mUserName1 ,那么我不能,因为它是EditText而不是String

EditProfileActivity EditProfileActivity

public class EditProfileActivity extends AppCompatActivity {

    ImageView mClose, mCheckmark, mImageProfile;
    TextView mChangePhoto;
    MaterialEditText mName, mUsername, mBio;

    private String mUsername1;
    private String mUsername2;

    FirebaseUser mFirebaseUser;

    private Uri mImageUri;
    StorageReference mStorageReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        mClose = findViewById(R.id.close);
        mCheckmark = findViewById(R.id.post_checkmark);
        mImageProfile = findViewById(R.id.image_profile);
        mChangePhoto = findViewById(R.id.text_view_change_profile_picture);
        mName = findViewById(R.id.fullname);
        mUsername = findViewById(R.id.username);
        mBio = findViewById(R.id.bio);

        mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        mStorageReference = FirebaseStorage.getInstance().getReference("uploads");

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(mFirebaseUser.getUid());
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user != null) {
                    mName.setText(user.getFullname());
                    mUsername.setText(user.getUsername().toLowerCase());
                    mBio.setText(user.getBio());
                    Glide.with(getApplicationContext()).load(user.getImageurl()).into(mImageProfile);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        mClose.setOnClickListener(v -> new AlertDialog.Builder(EditProfileActivity.this)
                .setMessage("Exit without saving changes?")
                .setPositiveButton("Yes", (dialog, which) -> {
                    finish();
                }).setNegativeButton("No", null).show());

        mChangePhoto.setOnClickListener(v -> CropImage.activity()
                .setAspectRatio(1, 1)
                .setCropShape(CropImageView.CropShape.OVAL)
                .start(EditProfileActivity.this));

        mImageProfile.setOnClickListener(v -> CropImage.activity()
                .setAspectRatio(1, 1)
                .setCropShape(CropImageView.CropShape.OVAL)
                .start(EditProfileActivity.this));

        mCheckmark.setOnClickListener(v -> {

            String str_name = mName.getText().toString();
            String str_username = mUsername.getText().toString();
            String str_bio = mBio.getText().toString();

            if (TextUtils.isEmpty(str_username) || TextUtils.isEmpty(str_bio) || TextUtils.isEmpty(str_name)) {
                Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
            } else if (str_username.length() > 20) {
                Toast.makeText(this, "Username cannot contain more than 20 characters", Toast.LENGTH_SHORT).show();
            } else {
                updateProfile(mName.getText().toString(), mUsername.getText().toString().toLowerCase(), mBio.getText().toString());
            }
        });
    }

    private void updateProfile(String fullname, String username, String bio) {
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(mFirebaseUser.getUid());

        mUsername1 = username.replaceAll("\\s+", "");
        mUsername1 = username.replaceAll("[^\\w]", "");

        DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Users");
        reference1.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapshot.getValue(User.class);
                    if (user != null) {
                        if (user.getUsername().equals(mUsername1)) {
                            Toast.makeText(EditProfileActivity.this, "That username is already in use", Toast.LENGTH_SHORT).show();
                        } else {
                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("fullname", fullname);
                            hashMap.put("username", mUsername1.toLowerCase());
                            hashMap.put("bio", bio);

                            reference.updateChildren(hashMap);
                        }
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

Add a break statement after the toast message.在 toast 消息之后添加一个 break 语句。 As you loop around a list of user objects from the data snapshot.当您从数据快照中循环用户对象列表时。 Also, You need to search for all the user object before saving.此外,您需要在保存前搜索所有用户 object。

 if (user.getUsername().equals(mUsername1)) {
                        Toast.makeText(EditProfileActivity.this, "That username is already in use", Toast.LENGTH_SHORT).show();
break;
                    }

Updates code -更新代码 -

       DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Users");
            reference1.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
      boolean ifUserNameExist = false;
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        User user = snapshot.getValue(User.class);
                        if (user != null) {
                            if (user.getUsername().equals(mUsername1)) {
                                Toast.makeText(EditProfileActivity.this, "That username is already in use", Toast.LENGTH_SHORT).show();
                           ifUserNameExist = true;
                            } 
                        }
                    }
if(!ifUserNameExist){
   HashMap<String, Object> hashMap = new HashMap<>();
                                hashMap.put("fullname", fullname);
                                hashMap.put("username", mUsername1.toLowerCase());
                                hashMap.put("bio", bio);

                                reference1.updateChildren(hashMap);
}
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查询数据库以确保新用户不会使用现有用户名注册 - Querying database to make sure new users don't register with an already existing username 错误:使用此用户名的用户不存在:使用 spring 安全性时 - Error: User doesn't exist with this username: when using spring security Java,请确保用户未在字符串中输入数字 - Java, make sure that a user doesn't enter numbers in a string 如何确保用户不输入字母 - How to make sure user doesn't enter letters 我如何确保添加到数组的对象的 ID 不存在而不会出现 nullpointerexception? - How do i make sure that the ID of object im adding to array doesn't exist without getting nullpointerexception? 在我的应用程序中,我使用的是sdk 25.0.0,但是当我运行它时,它需要的是不存在的sdk并需要下载的26.0.2 - in in my application i use sdk 25.0.0 but when i run it requires 26.0.2 that doesn't exist sdk and wants to download it, 休眠数据库名称更改使MySQLSyntaxErrorException:表不存在 - Hibernate database name change gives MySQLSyntaxErrorException: Table doesn't exist 如何确保用户名在我的数据库中不重复? - How do I make sure username is not repeated in my database? 如何制作不覆盖现有实例的 object 的新实例? - How to make a new instance of an object that doesn't overwrite the existing one? 即使用户名和密码存在于数据库中并且有效,“用户名或密码不匹配” - “User Name or Password does not match” even when the username and pass exist in database and are valid
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM