Sunday 26 September 2010

Making Asynchronous calls in Android

I am sharing today a code snippet by which you can make an Asynchronous call in Android


It will be better that this Asynchronous class should be made as an inner class in an activity in which you wants to have an Asynchornous call and dont let UI hang till the process is completed.

private class AsyncClass extends AsyncTask {

        private final ProgressDialog dialog = new ProgressDialog(ABCActivity.this);
       
       
       
        @Override
        protected Void doInBackground(String... params) {
           
            //Make a call here during which you wants that UI shouldnt be hang. Making a server hit or saving something into DB etc. Remember the stuff added here should be non-UI.
           
            return null;
        }
       
       
        protected void onPreExecute() {
            dialog.setMessage("Fetching info...");
            dialog.setCancelable(false);
            dialog.show();






//Here you can add UI stuff which you wanted to show before making the sync call.
           
        }
       
        protected void onPostExecute(final Void unused) {
            if (dialog.isShowing()) {
                dialog.dismiss();
                               
            }
           
           //Here you can add UI stuff which you wanted to show after making the sync call.
       
        }

    }