2

I am trying to verify if a username already exists in the Firebase DB and created a method to verify it.

The method should return true if the username is available and return false if the username is already taken.

public boolean isUsernameValid(final String newUsername, String oldUsername){
    if(newUsername.equals(oldUsername)){
        //if username is not changed
        return true;
    }else {
        userValid = true;
        databaseReference.orderByChild("Username").equalTo(newUsername).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                long userCount = dataSnapshot.getChildrenCount();
                if(userCount!=0){
                    userValid = false;
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }

        });
        return userValid;   //username is valid if this returns true
    }
}

this method is returning UserValid boolean first and then it is querying the database. Please let me know if I missed something.

This is returning true first, and then searching the DB for username and hence, it is always Overwriting the username in the DB.

This method is called from here:

    if(!TextUtils.isEmpty(str_firstName)
                && !TextUtils.isEmpty(str_lastName)
                && !TextUtils.isEmpty(str_username)
                && verify.isEmailValid(str_email)
                && verify.isMobileNoValid(str_mobile)

//here
                && verify.isUserNameValid(str_username, globalSharedPrefs.getUserDetail("username").toString())){
            progressDialog.setMessage("Saving Profile ...");
            progressDialog.show();

            //saving the photo
            if(isImageClicked) {
                filepath = storageReference.child("profile_photos").child(globalSharedPrefs.getUserDetail("uid").toString());
                filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //TODO: add picture remote/edit button in the XML
                        isImageClicked = false;
                        downloadUri = taskSnapshot.getDownloadUrl();
                        databaseReference.child("Profile Picture").setValue(downloadUri.toString());
                        uploadUserInfo();
                        Toast.makeText(UserProfileActivity.this, "Profile Saved.!", Toast.LENGTH_LONG)
                                .show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        updateProfileUI();
                        clickEditProfileButton(false);
                        Toast.makeText(UserProfileActivity.this, "Update Failed.!", Toast.LENGTH_LONG)
                                .show();
                    }
                });
            }

Database Structure

   {
  "userinfo" : {
    "J6Y4Dtxe7Nh45B653U5AVXHFrSJ2" : {
      "AccountId" : "",
      "DOB" : "21 Jun, 2017",
      "First Name" : "Krishna",
      "Last Name" : "kk",
      "Mobile" : "",
      "Username" : "kittuov",
      "uid" : "J6Y4Dtxe7Nh45B653U5AVXHFrSJ2"
    },
    "ck8x94FeHtUbC9DgHCkxmQt93Ar1" : {
      "AccountId" : "",
      "DOB" : "7 Dec, 1992",
      "First Name" : "Seshagiri Rao",
      "Last Name" : "Kornepati",
      "Mobile" : "",
      "Username" : "seshu1",
      "uid" : "ck8x94FeHtUbC9DgHCkxmQt93Ar1"
    },
    "iDBn0lYIZFSgll9KyVje0T6JFIy2" : {
      "AccountId" : "",
      "DOB" : "",
      "First Name" : "Ramesh",
      "Last Name" : "Devarapu",
      "Mobile" : "",
      "Username" : "rameshb",
      "uid" : "iDBn0lYIZFSgll9KyVje0T6JFIy2"
    }
  }
Community
  • 1
  • 1
  • Firebase asynchronously loads data. This means that by the time your `return` statement executes, the data hasn't loaded yet (try it by setting a breakpoint). For a broader explanation, see my answer here: https://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener – Frank van Puffelen Jun 18 '17 at 02:07

1 Answers1

0

Try this

if(str_username.equals(globalSharedPrefs.getUserDetail("username").toString()))){
    sumbit();
}else {

    databaseReference.orderByChild("Username").equalTo(newUsername).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            long userCount = dataSnapshot.getChildrenCount();
            if(userCount==0){
                sumbit();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

    private void sumbit(){
if(!TextUtils.isEmpty(str_firstName)
           && !TextUtils.isEmpty(str_lastName)
           && !TextUtils.isEmpty(str_username)
           && verify.isEmailValid(str_email)
           && verify.isMobileNoValid(str_mobile)
        ){
       progressDialog.setMessage("Saving Profile ...");
       progressDialog.show();

       //saving the photo
       if(isImageClicked) {
           filepath = storageReference.child("profile_photos").child(globalSharedPrefs.getUserDetail("uid").toString());
           filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
               @Override
               public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                   //TODO: add picture remote/edit button in the XML
                   isImageClicked = false;
                   downloadUri = taskSnapshot.getDownloadUrl();
                   databaseReference.child("Profile Picture").setValue(downloadUri.toString());
                   uploadUserInfo();
                   Toast.makeText(UserProfileActivity.this, "Profile Saved.!", Toast.LENGTH_LONG)
                           .show();
               }
           }).addOnFailureListener(new OnFailureListener() {
               @Override
               public void onFailure(@NonNull Exception e) {
                   progressDialog.dismiss();
                   updateProfileUI();
                   clickEditProfileButton(false);
                   Toast.makeText(UserProfileActivity.this, "Update Failed.!", Toast.LENGTH_LONG)
                           .show();
               }
           });
       }
       }
Martin De Simone
  • 2,108
  • 3
  • 16
  • 30