Friday, 25 October 2013

AsyncroTask Example To Get Server Data


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


Program Code  :

  Asyncronoustask.class

public class Asyncronoustask extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.example);
        
         
        final Button GetServerData = (Button) findViewById(R.id.btuserver);
        
        GetServerData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String serverURL = "http://www.mobile-tech.in/"; 
new LongOperation().execute(serverURL);
}
        });
        
    }
    
    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(Asyncronoustask.this);
        TextView uiUpdate = (TextView) findViewById(R.id.output);
        protected void onPreExecute() {
       
        uiUpdate.setText("Output : ");
            Dialog.setMessage("Downloading source..");
            Dialog.show();
        }

        protected Void doInBackground(String... urls) {
            try {
           
           
      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) {
       
            Dialog.dismiss();
            
            if (Error != null) {
                
                uiUpdate.setText("Output : "+Error);
                
            } else {
           
            uiUpdate.setText("Output : "+Content);
           
             }
        }
        
    }
}


Main.xml  :

 <Button 
        android:paddingTop="10px"
        android:id="@+id/btuserver" 
    android:text="Get Data Server " 
    android:cursorVisible="true"
    android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"  
android:layout_gravity="center_horizontal"
    /> 
    
    <TextView
        android:paddingTop="20px"
        android:id="@+id/output"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Data Will Display here" />



Out Put :

1.       


2 .    


3 .