Home > database >  How to update user data without changes into Firestore when it's checking for already existence
How to update user data without changes into Firestore when it's checking for already existence

Time:10-21

I recently implemented unique username into my app when registering, all good far here, by the way I also need to set it to when the user is editting it's profile.

I tried to do the same thing, but I'm facing an issue here. The app don't let save the profile, because it's checking if the username's taken and, as we're already using one, it won't let us do it.

Ex.: My username is "bob", I changed my profile pic or my display name, so when I click to save, the app will do a username checking in the background and will not let me save it because the username is already taken, but the problem is that it's already my user.

I've tried to set this, but failed:

if (document.equals(setup_username.getText().toString()) || document.isEmpty()){
    updateProfile();

Here's my code:

setup_progressbar.setVisibility(View.VISIBLE);
FirebaseFirestore.getInstance().collection("Users").whereEqualTo("username",setup_username.getText().toString()).get().addOnCompleteListener((task) -> {
    if (task.isSuccessful()){
        List<DocumentSnapshot> document = task.getResult().getDocuments();
        if (document.equals(setup_username.getText().toString()) || document.isEmpty()){
            updateProfile();
        } else {
            setup_progressbar.setVisibility(View.INVISIBLE);
            setup_username.setError(getString(R.string.username_taken));
            return;
        }
    } else {
        setup_progressbar.setVisibility(View.INVISIBLE);
        String error = task.getException().getMessage();
        FancyToast.makeText(getApplicationContext(), error, FancyToast.LENGTH_SHORT, FancyToast.ERROR, false).show();
    }
});

So how to get around this and only forbid it when I try to change my username to another that is taken? Like: "bob" to "bill", but "bill" is already taken, so it won't allow.

CodePudding user response:

You'll need to have some indication in each Users document to indicate which user has claimed that specific name. Given that you store the username inside the document, ownership would typically be established by using the UID of the user as the ID of the document.

Once you have run your query to find the document for the username, you can then check the UID of the owner of that username against the currently signed in user. If the two UIDs are the same, the current user owns the username and is allowed to update the document.

CodePudding user response:

Compare new username with previous username(store it in a variable while displaying user profile data), if both are same don't update it all else check for its uniqueness. or if you don't have existing username data create relationship with that document and fetch previous username first.

  • Related