Android asynctask usage and error handling-change UI components only on the main thread

Source: Internet
Author: User

You will always use the Asynctask class, especially in the network processing, first look at the corrected code: this is the normal code:

Class Sendkeytask extends asynctask<string, void, integer>{@Overrideprotected void OnPostExecute (Integer ResultCode) {//TODO auto-generated method Stubsuper.onpostexecute (ResultCode); switch (resultcode) {Case 6000: Notifyhelper.popnotifyinfo (innerquestionactivity.this, "User Information exception", ""); Break;case 6001:notifyhelper.popnotifyinfo ( Innerquestionactivity.this, "Other anomalies", ""); break;case 6002:break;default:break;} Hidden Input Method Inputmethodmanager Imm = (Inputmethodmanager) getapplicationcontext (). Getsystemservice (Context.input_method _service);//Show or hide Input method imm.togglesoftinput (0, inputmethodmanager.hide_not_always); Innerquestionedit.settext (""); /Refresh New Getquestiondetailtack (). Execute (1);} @Overrideprotected Integer doinbackground (String ... data) {//TODO auto-generated method Stubint resultcode=4001; HttpClient client= new Defaulthttpclient (); HttpPost post = new HttpPost ("http://diandianapp.sinaapp.com/add_key.php"); StringBuilder builder = new StringBuilder (); List<namevaluepair> paramslist=new ARraylist<namevaluepair> ();p Aramslist.add (New Basicnamevaluepair ("Access_token", Data[0]);p Aramslist.add ( New Basicnamevaluepair ("user_name", Data[1]));p Aramslist.add (New Basicnamevaluepair ("Key_detail", data[2])); Paramslist.add (New Basicnamevaluepair ("question_id", Data[3])); for (int i=0;i<jpegdatalist.size (); i++) { Paramslist.add (New Basicnamevaluepair ("img" +string.valueof (i), jpegdatalist.get (i))); try {post.setentity (new urlencodedformentity (paramslist,http). utf_8));} catch (Unsupportedencodingexception E1) {e1.printstacktrace ();} try {httpresponse response = Client.execute (POST); httpentity entity = response.getentity (); BufferedReader reader = new BufferedReader (New InputStreamReader (Entity.getcontent ())); for (String s = reader.readline (); s! = null; s = Reader.readline ()) {builder.append (s);} Jsonobject jsonobject = new Jsonobject (builder.tostring ()); String statecodestr = jsonobject.getstring ("State_code"); Resultcode=integer.parseint (STATECODESTR);} catch (ClientProtocolException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();//Processing request failed}finally{}return ResultCode;}}

Someone might say, I let doinbackground return a parameter, and then handle it in OnPostExecute not multiple times? However, when you really combine the two parts, you will find that the error! The error content is generally UI content can only be changed in the main thread;

Notifyhelper.popnotifyinfo (Innerquestionactivity.this, "Other exception", "") is a pop-up method wrapper for the dialog box, which is the action on the UI interface, the problem should be here!

Let's look at Google's instructions:

protected abstract ResultDoinbackground (params ... params)Added in API Level 3

Override This method to perform a computation on a background thread. The specified parameters is the parameters passed to by the caller of this execute(Params...) task. This method can call to publishProgress(Progress...) publish updates on the UI thread.

Parameters
Params The parameters of the task.
Returns
    • A result, defined by the subclass of this task.

protected voidOnPostExecute(result result)Added in API Level 3

Runs the UI thread after doInBackground(Params...) . The specified result is the value of returned by doInBackground(Params...) .

This method won ' t is invoked if the task was cancelled.

Parameters
Result The result of the operation computed by doInBackground(Params...) .
See Alsoprotected voidOnPreExecute()Added in API Level 3

Runs on the UI thread before doInBackground(Params...) .

As we can see, these overloaded methods only Doinbackground are running in the background thread, and the latter cannot perform the update thread operation!

We have to return the processing results of the time-consuming operation in Doinbackground, and then do the UI components from the OnPostExecute based on the parameters returned by Doinbackground!



Doinbackground

Android asynctask usage and error handling-change UI components only on the main thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.