0

I am doing a validation for fields in an android form.I am checking with server whether the username is available in the server or not.But the main thread goes to the next page before the async checking completes.

The code:

btnnext1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

        isallValid=true;
        //check second time for username validation(first time was in onfocus changed)

//      if(txtusername.getText().toString().trim().equals("achuthan")){
//          txtusername.setError("Username exsists!");
//          isUsernameValid=false;
//        }
//      
//        else
//        {
//          isUsernameValid=true;
//        }

        try {
            Void async_result=new validateusername().execute().get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

                if(txtfullname.getText().toString().trim().length()==0)
            {
            txtfullname.requestFocus();
            txtfullname.setError("Field required");
            isallValid=false;

            }
        if(txtdob.getText().toString().trim().length()==0)
        {
            txtdob.requestFocus();
            txtdob.setError("Field required");
            isallValid=false;
        }
        if(txtoccupation.getText().toString().trim().length()==0)
        {
            txtoccupation.requestFocus();
            txtoccupation.setError("Field required");
            isallValid=false;
        }
         if(txtusername.getText().toString().trim().length()<6){
            txtusername.requestFocus();
            txtusername.setError("Minimum length of 6 characters");
            isallValid=false;
        }
        if(txtpassword.getText().toString().trim().length()==0)
        {
            txtpassword.requestFocus();
            txtpassword.setError("Field required");
            isallValid=false;
        }
        if(txtconfirmpassword.getText().toString().trim().length()==0)
        {
            txtconfirmpassword.requestFocus();
            txtconfirmpassword.setError("Field required");
            isallValid=false;
        }
        else if(!txtpassword.getText().toString().trim().equals(txtconfirmpassword.getText().toString().trim()))
        {
            //txtconfirmpassword.requestFocus();
            txtconfirmpassword.setError("Passwords not equal");
            txtpassword.setError("Passwords not equal");
            isallValid=false;
        }


         if(isallValid&&isUsernameValid)
        {
            //Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show();
            ((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim();
            ((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim();


            int id=radiogender.getCheckedRadioButtonId();
            RadioButton rb=(RadioButton) view.findViewById(id);
            String gender=rb.getText().toString();
            ((SignUpPage)getActivity()).getValues().gender=gender;


            int id1=radiomarital.getCheckedRadioButtonId();
            RadioButton rb1=(RadioButton) view.findViewById(id1);
            String marital_status=rb1.getText().toString();
            ((SignUpPage)getActivity()).getValues().marital_status=marital_status;



            ((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim();
            ((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim();
            ((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim();



            ((SignUpPage)getActivity()).selectFragment(1);


        }
                    //if all valid , store values and go to next fragment
                    //((SignUpPage)getActivity()).selectFragment(1);
            }
        });



        return view;
    }

The async class:

public class validateusername extends AsyncTask<String,Void,Void>
        {

            @Override
            protected Void doInBackground(String... arg0) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                pairs.add(new BasicNameValuePair("username",txtusername.getText().toString().trim()));
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(pairs));
                    response = httpclient.execute(httppost);
                    result=responsetostring.getResponseBody(response);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }




                return null;
            }
            @Override
            protected void onPostExecute(Void result1) {
                try {
                    jsonobj=new JSONObject(result);
                    job2=jsonobj.getJSONObject("server_message");
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                 try {
                    finalresult=job2.getString("username_availability_message");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(finalresult.equals("exist")){
                    txtusername.setError("Username exsists!");
                    isUsernameValid=false;
                }
                else if(finalresult.equals("available"))
                {

                    isUsernameValid=true;
                }
            }

        }

I tried using the get method so that the main thread waits till the async class finishes but it didnt work.Please help!!

codebot
  • 2,540
  • 3
  • 38
  • 89
Achuthan M
  • 349
  • 1
  • 4
  • 17

2 Answers2

2

Check isallValid only in button click , then Do this validation inside your onPostExecute(Void result) method,

  if(isUsernameValid)
    {
        //Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show();
        ((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim();
        ((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim();


        int id=radiogender.getCheckedRadioButtonId();
        RadioButton rb=(RadioButton) view.findViewById(id);
        String gender=rb.getText().toString();
        ((SignUpPage)getActivity()).getValues().gender=gender;


        int id1=radiomarital.getCheckedRadioButtonId();
        RadioButton rb1=(RadioButton) view.findViewById(id1);
        String marital_status=rb1.getText().toString();
        ((SignUpPage)getActivity()).getValues().marital_status=marital_status;



        ((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim();
        ((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim();
        ((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim();



        ((SignUpPage)getActivity()).selectFragment(1);


    }

now it will work.................

Karthick pop
  • 616
  • 3
  • 16
  • But i am calling the async class twice.Once in the onfocuschanged listener of the username field.So the post execute would run in that case too. – Achuthan M Sep 30 '14 at 07:08
0

Do not use get() to call the AsyncTask, it hangs your UI.

So call your AsyncTask like,

String userName = txtusername.getText().toString().trim();
new validateusername().execute(userName);     // pass the String from EditText, as you cannot interact with UI in doInBackground

Modify your AsyncTask like

 public class validateusername extends AsyncTask<String,Void,String>
    { 

        @Override 
        protected String doInBackground(String... arg0) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("username",arg0[0]));    // arg0[0] is the username passed from AsyncTask call
            try { 

                httppost.setEntity(new UrlEncodedFormEntity(pairs));
                response = httpclient.execute(httppost);
                result=responsetostring.getResponseBody(response); 
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block 
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block 
                e.printStackTrace();
            } 




            return result; 
        } 



        @Override 
        protected void onPostExecute(String result1) {
            try { 
                jsonobj=new JSONObject(result);
                job2=jsonobj.getJSONObject("server_message"); 
            } catch (JSONException e1) {
                // TODO Auto-generated catch block 
                e1.printStackTrace();
            } 
             try { 
                finalresult=job2.getString("username_availability_message"); 
            } catch (JSONException e) {
                // TODO Auto-generated catch block 
                e.printStackTrace();
            } 
            if(finalresult.equals("exist")){ 
                txtusername.setError("Username exsists!"); 
                isUsernameValid=false; 
            } 
            else if(finalresult.equals("available")) 
            { 

                isUsernameValid=true; 
            } 





 if(txtfullname.getText().toString().trim().length()==0) 
    { 
    txtfullname.requestFocus(); 
    txtfullname.setError("Field required"); 
    isallValid=false; 

    } 
if(txtdob.getText().toString().trim().length()==0) 
{ 
    txtdob.requestFocus(); 
    txtdob.setError("Field required"); 
    isallValid=false; 
} 
if(txtoccupation.getText().toString().trim().length()==0) 
{ 
    txtoccupation.requestFocus(); 
    txtoccupation.setError("Field required"); 
    isallValid=false; 
} 
 if(txtusername.getText().toString().trim().length()<6){ 
    txtusername.requestFocus(); 
    txtusername.setError("Minimum length of 6 characters"); 
    isallValid=false; 
} 
if(txtpassword.getText().toString().trim().length()==0) 
{ 
    txtpassword.requestFocus(); 
    txtpassword.setError("Field required"); 
    isallValid=false; 
} 
if(txtconfirmpassword.getText().toString().trim().length()==0) 
{ 
    txtconfirmpassword.requestFocus(); 
    txtconfirmpassword.setError("Field required"); 
    isallValid=false; 
} 
else if(!txtpassword.getText().toString().trim().equals(txtconfirmpassword.getText().toString().trim())) 
{ 
    //txtconfirmpassword.requestFocus(); 
    txtconfirmpassword.setError("Passwords not equal"); 
    txtpassword.setError("Passwords not equal"); 
    isallValid=false; 
} 


 if(isallValid&&isUsernameValid) 
{ 
    //Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show(); 
    ((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim(); 
    ((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim(); 


    int id=radiogender.getCheckedRadioButtonId();
    RadioButton rb=(RadioButton) view.findViewById(id);
    String gender=rb.getText().toString();
    ((SignUpPage)getActivity()).getValues().gender=gender;


    int id1=radiomarital.getCheckedRadioButtonId();
    RadioButton rb1=(RadioButton) view.findViewById(id1);
    String marital_status=rb1.getText().toString();
    ((SignUpPage)getActivity()).getValues().marital_status=marital_status;



    ((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim(); 
    ((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim(); 
    ((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim(); 



    ((SignUpPage)getActivity()).selectFragment(1); 


  } 
}  

onPostExecute(), check the conditions and navigate to next activity.

Aniruddha
  • 4,477
  • 2
  • 21
  • 39