title: advice on checking username availability in an edittext in android
body: <p>I have a project where there is a registration form with multiple fields.One of the fields is for user name.I want to check whether the value entered in the edittext for the username is available or not.So i tried using onfocuslistener , that is when the ishasfocus variable is false a request goes to the server.I have tried the following:</p>
  
  <pre><code>txtusername.setOnFocusChangeListener(new View.OnFocusChangeListener()
          {
              @Override
              public void onFocusChange(View v, boolean hasFocus)
              {
                  if (!hasFocus)
                  {
  
                       username=txtusername.getText().toString().trim();
                  if(username.equals("achuthan")){
                      txtusername.setError("Username exsists!");
                      isUsernameValid=false;
                  }
                  else
                  {
                      isUsernameValid=true;
                  }
              }
              }
          });
  </code></pre>
  
  <p>and in the button click for the submit button i check  whether <code>isUsernameValid</code> is true.</p>
  
  <p>The issue is this:</p>
  
  <p>The checking whether the username is valid happens when i leave the edittext to the next one.So when i type an invalid username(achuthan in this case) and then leave to the next field the boolean value is set as false and the error is shown.Now if i correct the username to a valid one ,but if i dont leave focus of the edittext and press submit , the form is not getting accepted(Since the boolean value has not changed to true, which happens in the else part).How do i resolve this issue?</p>
  
  <p>EDIT:Tried this didnt work</p>
  
  <pre><code>txtusername.setOnFocusChangeListener(new View.OnFocusChangeListener()
          {
              @Override
              public void onFocusChange(View v, boolean hasFocus)
              {
                  isUsernameValid=true;
                  if (!hasFocus||hasFocus)
                  {
                      //check with server if username exsists,if exsists isUserNameValid=true else false
                       username=txtusername.getText().toString().trim();
                  if(username.equals("achuthan")){
                      txtusername.setError("Username exsists!");
                      isUsernameValid=false;
                  }
                  else
                  {
                      isUsernameValid=true;
                  }
              }
              }
          });
  </code></pre>