AsyncroTask Example To Get Server Data - Android Example

DOWNLOAD CODE

Related Examples

AsyncroTask Basics:

     1.  AsyncTask provide easy way to use of the UI thread.
 
     2.  Perform background operations and publish results on the UI thread without having to     manipulate threads and/or handlers.

      3.  AsyncTask is designed to be a helper class around Thread and Handler and does not use a generic threading framework.

     4.  AsyncTasks should ideally be used for short operations (a few seconds at the most.)

     5.  The AsyncTask class must be loaded on the UI thread.

      6. The task instance must be created on the UI thread.

      7.   execute(Params...)  must be invoked on the UI thread.

Usage:

Taking same example as we have done in previous example Thread With Handlers - Android Example

In this example  we are creating a thread and call http GET method to get server response and after got the response,then do other functionality ( Save Data in database or show alert ,Redirect to another activity).

 

Project Structure :

 

AsyncronousTask_project_sketch

 

AsyncronoustaskAndroidExample.java File :

Create button refference:

 

    final Button GetServerData = (Button) findViewById(R.id.GetServerData);

On Botton click:

Inside button click listener create LongOpertion Object and call excecute method

 


       GetServerData.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                
                // Server Request URL
                String serverURL = "/media/webservice/getPage.php";
                
                // Create Object and call AsyncTask execute Method
                new LongOperation().execute(serverURL);
                
            }
        });  

 

onPreExecute() Method :

After call execute() method  onPreExecute() will call and show dialog.
 Inside onPreExecute() we can update UI elements.

 


          protected void onPreExecute() {
                    // NOTE: You can call UI Element here.
                    
                    //UI Element
                    uiUpdate.setText("Output : ");
                    Dialog.setMessage("Downloading source..");
                    Dialog.show();
            }

 

doInBackground(String... urls) Method :

Just after complition of onPreExecute() method doInBackground() will call
 Inside doInBackground we will take background processing ( Request to server )
 NOTE : Inside doInBackground() we can not update UI elements.

 




    // Call after onPreExecute method

     protected Void doInBackground(String... urls) {
            try {
                
                // Call long running operations here (perform background computation)
                // NOTE: Don't call UI Element here.
                
                // Server url call by GET method
                HttpGet httpget = new HttpGet(urls[0]);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                Content = Client.execute(httpget, responseHandler);
                
            } catch (ClientProtocolException e) {
                Error = e.getMessage();
                cancel(true);
            } catch (IOException e) {
                Error = e.getMessage();
                cancel(true);
            }
            
            return null;
        }


 

onPostExecute() Method :

Just after doInBackground() method processed ( Done all background tasks ) , onPostExecute method call.
 Inside onPostExecute() we can update UI elements.

 


    protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.
            
            // Close progress dialog
            Dialog.dismiss();
            
            if (Error != null) {
                
                uiUpdate.setText("Output : "+Error);
                
            } else {
                
                uiUpdate.setText("Output : "+Content);
                
             }
        }

 

Complete AsyncronoustaskAndroidExample.java File :

 


    public class AsyncronoustaskAndroidExample extends Activity {
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
        
            super.onCreate(savedInstanceState);
            setContentView(R.layout.asyncronoustask_android_example);
            
            final Button GetServerData = (Button) findViewById(R.id.GetServerData);
            
            GetServerData.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    
                    // Server Request URL
                    String serverURL = "/media/webservice/getPage.php";
                    
                    // Create Object and call AsyncTask execute Method
                    new LongOperation().execute(serverURL);
                    
                }
            });    
            
        }
        
        
        // Class with extends AsyncTask class
        private class LongOperation  extends AsyncTask<String, Void, Void> {
            
            private final HttpClient Client = new DefaultHttpClient();
            private String Content;
            private String Error = null;
            private ProgressDialog Dialog = new ProgressDialog(AsyncronoustaskAndroidExample.this);
            
            TextView uiUpdate = (TextView) findViewById(R.id.output);
            
            protected void onPreExecute() {
                // NOTE: You can call UI Element here.
                
                //UI Element
                uiUpdate.setText("Output : ");
                Dialog.setMessage("Downloading source..");
                Dialog.show();
            }
    
            // Call after onPreExecute method
            protected Void doInBackground(String... urls) {
                try {
                    
                    // Call long running operations here (perform background computation)
                    // NOTE: Don't call UI Element here.
                    
                    // Server url call by GET method
                    HttpGet httpget = new HttpGet(urls[0]);
                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    Content = Client.execute(httpget, responseHandler);
                    
                } catch (ClientProtocolException e) {
                    Error = e.getMessage();
                    cancel(true);
                } catch (IOException e) {
                    Error = e.getMessage();
                    cancel(true);
                }
                
                return null;
            }
            
            protected void onPostExecute(Void unused) {
                // NOTE: You can call UI Element here.
                
                // Close progress dialog
                Dialog.dismiss();
                
                if (Error != null) {
                    
                    uiUpdate.setText("Output : "+Error);
                    
                } else {
                    
                    uiUpdate.setText("Output : "+Content);
                    
                 }
            }
            
        }
    }