Tuesday, March 5, 2013

Main thread issue in Android | Async class demo in Android | Background Thread

Hello Friends,
Today I am going to share simple code for Async class in Android. At the time of development sometime we catch Main Thread exception for this we should use Async  or Background Thread. Hope my blog will help you-


import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;

public class AsyncClassTest extends Activity {

       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.screen_sign_up);
              /**
               * do what you want here Like- get textbox, imageview id's etc
               */

              // Call Async Class
              new getProfileimage().execute();

       }

       public class getProfileimage extends AsyncTask<String, Void, String> {

              ProgressDialog pd = null;

              @Override
              protected void onPreExecute() {
                     pd = ProgressDialog.show(AsyncClassTest.this, "Please wait",
                                  "Loading please wait..", true);
                     pd.setCancelable(true);

              }

              @Override
              protected String doInBackground(String... params) {
                     /**
                      * Do what you want here in background Thread Like- call any
                      * web service, get data from server and set into Listview etc.
                      */
                     return null;
              }

              @Override
              protected void onPostExecute(String result) {
                     pd.dismiss();
                     /**
                      * 1)dismiss progress dialog 2)do main thread task here like-
                      *  set view, make toast etc.
                      */
              }

       }

}

Note- 
1)See comments for help.
2)Don't do any View related task inside background thread.
3)For any help please comment on my blog.

Thanks,

4 comments:

  1. Hi Manish,
    nice tutorials.
    this is Srinivas, recently i have attended an interview for a company at that time interviewer asked me that how can you find the distance b/w two places and speed of a vehicle?

    could you answer me plz?

    ReplyDelete
    Replies
    1. yes using location manager you can get it..
      1)For distance get both vehicle lat,lon and then just call google api for distence between two places..
      2)For speed onLocation Change method just call-location.speed();

      You can try my this blog also-
      http://www.androidhub4you.com/2013/06/how-to-get-device-current-speed-in_112.html

      Delete
  2. Hi sir, Now i am working 1 min ago task,how to show all call in android

    ReplyDelete