UI线程在异步类在android中运行之前运行

时间:2014-09-30 06:50:06

标签: java android ui-thread

我正在对android表单中的字段进行验证。我正在检查服务器中的用户名是否可用。但是主线程在异步检查完成之前进入下一页。

代码:

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;
    }

异步类:

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;
                }
            }

        }

我尝试使用get方法,以便主线程等到异步类完成但它没有工作。请帮助!!

2 个答案:

答案 0 :(得分:2)

仅在按钮点击时检查isallValid,然后在onPostExecute(Void result)方法中执行此验证,

  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);


    }

现在它将起作用.................

答案 1 :(得分:0)

不要使用get()来调用AsyncTask,它会挂起你的UI。

所以请调用你的AsyncTask,

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

修改您的AsyncTask,如

 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(),检查条件并导航到下一个活动。