By Fox


2012-03-12 17:09:39 8 Comments

I was reading about AsyncTask, and I tried the simple program below. But it does not seem to work. How can I make it work?

public class AsyncTaskActivity extends Activity {

    Button btn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener) this);
    }

    public void onClick(View view){
        new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            for(int i=0;i<5;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

I am just trying to change the label after 5 seconds in the background process.

This is my main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="10dip">
    </ProgressBar>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" >
    </Button>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace"/>
</LinearLayout>

18 comments

@Ankush Shrivastava 2019-02-12 10:42:41

ASync Task;

public class MainActivity extends AppCompatActivity {

 private String ApiUrl="your_api";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     MyTask myTask=new MyTask();
     try {
         String result=myTask.execute(ApiUrl).get();
         Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
     } catch (ExecutionException e) {
         e.printStackTrace();
     } catch (InterruptedException e) {
        e.printStackTrace();
     }

  }


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


    @Override
    protected String doInBackground(String... strings) {
        String result="";
        HttpURLConnection httpURLConnection=null;
        URL url;

        try {
            url=new URL(strings[0]);
            httpURLConnection=(HttpURLConnection) url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            InputStreamReader reader=new InputStreamReader(inputStream);
            result=getData(reader);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String getData(InputStreamReader reader) throws IOException{
        String result="";
        int data=reader.read();
        while (data!=-1){
            char now=(char) data;
            result+=data;
            data=reader.read();
        }
        return result;
    }
  }
}

@Rohit Singh 2019-01-25 06:20:01

How to memorize the parameters used in AsyncTask?

Don't

If you are new to AsyncTask then it is very common to get confused while writing an AsyncTask. Main culprits are the parameters used in the AsyncTask ie AsyncTask<A,B,C>. Based on the A,B,C (arguments) signature of the methods differs which makes thing even more confusing.

Keep it simple!

The key is Don't memorize. If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature at the first attempt would be a piece of cake. Just figure out what your Input, Progress and Output are and you will be good to go.

So what is an AsyncTask?

AsyncTask are background task which run in the background thread. It takes an Input, performs Progress and gives Output.

ie AsyncTask<Input,Progress,Output>.

For example: enter image description here

What is the relationship with methods ?

Between AsyncTask and doInBackground()

enter image description here

doInBackground() and onPostExecute(),onProgressUpdate()` are also related

enter image description here

How to write that in the code?

DownloadTask extends AsyncTask<String,Integer,String>{

  // Always same signature
  @Override
  public void onPreExecute()
  {}

  @Override
  public String doInbackGround(String... params)
  {
           // Download code
           int downloadPerc = // calculate that
           publish(downloadPerc);

           return "Download Success";
  }

  @Override
  public void onPostExecute(String result)
  {
      super.onPostExecute(result);
  }

  @Override
  public void onProgressUpdate(Integer... params)
  {
         // show in spinner, access UI elements
  }

}

How will you run this Task?

new DownLoadTask().execute("Paradise.mp3");

@Däñish Shärmà 2019-01-28 13:49:09

Awesome explanation. Thanks

@Sazzad Hissain Khan 2018-11-14 09:38:59

Sample AsyncTask example with progress

import android.animation.ObjectAnimator;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AsyncTaskActivity extends AppCompatActivity implements View.OnClickListener {

    Button btn;
    ProgressBar progressBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(this);
        progressBar = (ProgressBar)findViewById(R.id.pbar);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                new LongOperation().execute("");
                break;
        }
    }

    private class LongOperation extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            Log.d("AsyncTask", "doInBackground");
            for (int i = 0; i < 5; i++) {
                try {
                    Log.d("AsyncTask", "task "+(i + 1));
                    publishProgress(i + 1);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Completed";
        }

        @Override
        protected void onPostExecute(String result) {
            Log.d("AsyncTask", "onPostExecute");
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText(result);
            progressBar.setProgress(0);
        }

        @Override
        protected void onPreExecute() {
            Log.d("AsyncTask", "onPreExecute");
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("onPreExecute");
            progressBar.setMax(500);
            progressBar.setProgress(0);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.d("AsyncTask", "onProgressUpdate "+values[0]);
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("onProgressUpdate "+values[0]);

            ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 100 * values[0]);
            animation.setDuration(1000);
            animation.setInterpolator(new LinearInterpolator());
            animation.start();
        }
    }
}

@TT-- 2017-09-17 16:20:03

Background / Theory

AsyncTask allows you to run a task on a background thread, while publishing results to the UI thread.

The user should always able to interact with the app so it is important to avoid blocking the main (UI) thread with tasks such as downloading content from the web.

This is why we use an AsyncTask.

It offers a straightforward interface by wrapping the UI thread message queue and handler that allow you to send and process runnable objects and messages from other threads.

Implementation

AsyncTask is a generic class. (It takes parameterized types in its constructor.)

It uses these three generic types:

Params - the type of the parameters sent to the task upon execution.

Progress - the type of the progress units published during the background computation.

Result - the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

These three parameters correspond to three primary functions you can override in AsyncTask:

  • doInBackground(Params...)
  • onProgressUpdate(Progress...)
  • onPostExecute(Result)

To execute AsyncTask

call execute() with parameters to be sent to the background task.

What Happens

  1. On main/UI thread, onPreExecute() is called. (To initialize something in this thread such as show a progress bar on the user interface.)

  2. On a background thread, doInBackground(Params...) is called. (The parameters are those passed to the Execute function.)

    • Where the long-running task should happen

    • Must override at least doInBackground() to use AsyncTask.

    • Call publishProgress(Progress...) to update a display of progress in the user interface while the background computation is still executing. (e.g. animate a progress bar or show logs in a text field.)

      • This causes onProgressUpdate() to be called.
  3. On the background thread, a result is returned from doInBackground(). This triggers the next step.

  4. On main/UI thread, onPostExecute() called with the returned result.

Examples

Using again the example of the blocking task being to download something from the web,

  • Example A downloads an image and displays it in an ImageView,
  • while Example B downloads some files.

Example A

The doInBackground() method downloads the image and stores it in an object of type BitMap. The onPostExecute() method takes the bitmap and places it in the ImageView.

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bitImage;

    public DownloadImageTask(ImageView bitImage) {
        this.bitImage = bitImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mBmp = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mBmp = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mBmp;
    }

    protected void onPostExecute(Bitmap result) {
        bitImage.setImageBitmap(result);
    }
}

Example B

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Example B execution

new DownloadFilesTask().execute(url1, url2, url3);

@KGCybeX 2018-05-26 17:00:08

Thanks for taking the time to explain it!

@john ktejik 2018-10-09 04:44:01

Very nice.. But I keep getting error about return type clashing - attempting to use incompatible return type. I have tried all sorts of return types, same error.

@nitesh 2013-09-16 12:02:21

Concept and code here

I have created a simple example for using AsyncTask of Android. It starts with onPreExecute(), doInBackground(), publishProgress() and finally onProgressUpdate().

In this doInBackground() works as a background thread, while other works in the UI Thread. You can't access an UI element in doInBackground(). The sequence is same as I have mentioned.

However if you need to update any widget from doInBackground you can publishProgress from doInBackground which will call onProgressUpdate to update your UI widget.

class TestAsync extends AsyncTask<Void, Integer, String>
{
    String TAG = getClass().getSimpleName();

    protected void onPreExecute (){
        super.onPreExecute();
        Log.d(TAG + " PreExceute","On pre Exceute......");
    }

    protected String doInBackground(Void...arg0) {
        Log.d(TAG + " DoINBackGround","On doInBackground...");

        for(int i=0; i<10; i++){
            Integer in = new Integer(i);
            publishProgress(i);
        }
        return "You are at PostExecute";
    }

    protected void onProgressUpdate(Integer...a){
        super.onProgressUpdate(a);
        Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.d(TAG + " onPostExecute", "" + result);
    }
}

Call it like this in your activity:

new TestAsync().execute();

Developer Reference Here

@Vamsi Pavan Mahesh 2014-03-13 15:35:11

classes starts with generally capital letters in Java , that's a notation usually followed

@bbedward 2012-03-12 17:15:07

I'm sure it is executing properly, but you're trying to change the UI elements in the background thread and that won't do.

Revise your call and AsyncTask as follows:

Calling Class

Note: I personally suggest using onPostExecute() wherever you execute your AsyncTask thread and not in the class that extends AsyncTask itself. I think it makes the code easier to read especially if you need the AsyncTask in multiple places handling the results slightly different.

new LongThread()
{
    @Override public void onPostExecute(String result)
    {
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText(result);
    }
}.execute("");

LongThread class (extends AsyncTask):

@Override
protected String doInBackground(String... params) {
    for(int i = 0; i < 5; i++) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    return "Executed";
}      

@sthomps 2014-08-07 19:11:10

Thanks for providing an example that decouples the AsyncTask from the Activity

@mcy 2017-05-25 08:56:57

yes, finally someone decouples the task and the activity. thank you.And overriding the onPostExecute in the activity is brilliant.

@Biswajit Karmakar 2016-05-15 07:55:26

Change your code as given below:

@Override
protected void onPostExecute(String result) {

    runOnUiThread(new Runnable() {
        public void run() {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
        }
    });
}

@justdan0227 2016-07-16 16:49:42

You shouldn't need to use runOnUiThread as onPostExecute always runs on thread 1 (does it not?)

@Krishna 2015-12-22 18:25:29

When you are in the worker thread, you can not directly manipulate UI elements on Android.

When you are using AsyncTask please understand the callback methods.

For example:

public class MyAyncTask extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        // Here you can show progress bar or something on the similar lines.
        // Since you are in a UI thread here.
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        // After completing execution of given task, control will return here.
        // Hence if you want to populate UI elements with fetched data, do it here.
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        // You can track you progress update here
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Here you are in the worker thread and you are not allowed to access UI thread from here.
        // Here you can perform network operations or any heavy operations you want.
        return null;
    }
}

FYI: To access the UI thread from a worker thread, you either use runOnUiThread() method or post method on your view.

For instance:

runOnUiThread(new Runnable() {
    textView.setText("something.");
});

or
    yourview.post(new Runnable() {
    yourview.setText("something");
});

This will help you know the things better. Hence in you case, you need to set your textview in the onPostExecute() method.

@user1728578 2015-02-06 06:39:05

Sample Async Task with POST request:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key1", "value2"));
new WEBSERVICEREQUESTOR(URL, params).execute();

class WEBSERVICEREQUESTOR extends AsyncTask<String, Integer, String>
{
    String URL;
    List<NameValuePair> parameters;

    private ProgressDialog pDialog;

    public WEBSERVICEREQUESTOR(String url, List<NameValuePair> params)
    {
        this.URL = url;
        this.parameters = params;
    }

    @Override
    protected void onPreExecute()
    {
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Processing Request...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params)
    {
        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            HttpPost httpPost = new HttpPost(URL);

            if (parameters != null)
            {
                httpPost.setEntity(new UrlEncodedFormEntity(parameters));
            }
            httpResponse = httpClient.execute(httpPost);

            httpEntity = httpResponse.getEntity();
            return EntityUtils.toString(httpEntity);

        }  catch (Exception e)
        {

        }
        return "";
    }

    @Override
    protected void onPostExecute(String result)
    {
        pDialog.dismiss();

        try
        {

        }
        catch (Exception e)
        {

        }
        super.onPostExecute(result);
    }
}

@Ebin Sebastian 2012-12-14 12:19:20

Simply:

LongOperation MyTask = new LongOperation();
MyTask.execute();

@Graham Smith 2012-03-12 17:12:49

Ok you are trying to access the GUI via another thread. This, in the main, is not good practice.

The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.

preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.

See these lines where you are later updating your TextView:

TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");

put them in PostExecute()

You will then see your TextView text updated after the doInBackground completes.

EDIT: I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.button1);
        // because we implement OnClickListener we only have to pass "this"
        // (much easier)
        btn.setOnClickListener(this);
    }

    public void onClick(View view) {
        // detect the view that was "clicked"
        switch (view.getId()) {
        case R.id.button1:
            new LongOperation().execute("");
            break;
        }
    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // might want to change "executed" for the returned string passed
            // into onPostExecute() but that is upto you
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}

@Fox 2012-03-12 17:33:22

I am unable to do this <code> btn.setOnClickListener(this); </code> Eclipse gives an error ----- "The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (AsyncTaskActivity)"

@Eric 2012-12-28 10:37:16

I would advise changing the setting of the text to not be static but take the argument from the onPostExecute(String result) method. It would make it clearer for future readers that the argument is populated by the return value of doInBackground(String... params).

@Graham Smith 2012-12-30 21:13:34

@Eric Tobias - That exact things done in the commented section already. I was following and answering the users question in my full example.

@Eric 2013-01-02 13:46:09

@Graham Indeed, I saw the comment. However, I think it is best not to refer to the static assignment at all. It is, in my opinion, a bad habit and should be avoided. Not to mention that such a wonderful response as yours has an obligation to teach good practices as well! ;)

@Eric 2013-01-03 08:05:17

@Graham Yes, lets not go to that dark place please! ;) Thank you for your correspondence. I now do understand your reason and can only agree. Thank you for taking the time to reply.

@RichieHH 2014-01-21 20:45:37

As an addendum and google seeder (and coming from someone currently learning this stuff which is how I came across this) : the majority of UI updates you'll do for something where you need progress reported back to the user is in the call back onProgressUpdate which is executed in the main UI thread.

@Sam 2014-09-09 12:43:57

This will surely mess up if your activity is rotated or destroyed for any reason...

@Graham Smith 2014-09-10 09:48:04

@Sam - Yes, but that is NOT what the OP was asking. The question relates to making an AsyncTask work not what the pit falls or alternatives are of using one.

@Sam 2014-09-10 13:02:12

Fair enough. Just pointing it out. It might be worth highlighting in the answer (esp as it's very highly up-voted) as this can be an easy way to shoot yourself in the foot.

@eawedat 2018-02-14 18:42:30

@Graham Smith, is it possible to access Views like TextView of another activity ( txt.setText("Executed");) within a separated AsyncTask's class? like to put the asynctask in a separated .java file (not as an inner class).

@Graham Smith 2018-02-15 13:16:47

There are ways of doing that, however I would not use AsyncTask for anything, as it is the path to a dark and horrid places.

@Suragch 2015-04-10 10:41:28

My full answer is here, but here is an explanatory image to supplement the other answers on this page. For me, understanding where all the variables were going was the most confusing part in the beginning.

enter image description here

@Zaffar Saffee 2015-05-22 20:36:07

the best and quick explanation of 3 params of AsyncTask....+1 for you

@Suragch 2016-02-02 01:29:57

params is an array. (In the example above, it was a String array.) This allows you to pass in multiple parameters of the same type. Then you can access those parameters with params[0], params[1], params[2], etc. In the example, there was only a single String in the params array. If you need to pass in multiple parameters of different types (for example, a String and an int), see this question.

@kc ochibili 2014-11-29 23:39:17

I would recommend making your life easier by using this library for background works https://github.com/Arasthel/AsyncJobLibrary

its this simple..

AsyncJob.doInBackground(new AsyncJob.OnBackgroundJob() {

    @Override
    public void doOnBackground() {
        startRecording();
    }
});

@Vaishali Sutariya 2014-08-26 04:12:11

 private class AsyncTaskDemo extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        //do code here 

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    @Override
    protected void onCancelled() {

        super.onCancelled();
        progressDialog.dismiss();
        Toast toast = Toast.makeText(getActivity(),
                "Error is occured due to some probelm", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 25, 400);
        toast.show();

    }

}

@Cristiana Chavez 2014-06-25 04:35:45

You need to declare the button onclicklistener, once click it calls AsyncTask class DownloadJson ,the process will be shown below:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             new DownloadJson().execute();
            }
        });

    }

     // DownloadJSON AsyncTask
    private class DownloadJson extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected  Void doInBackground(Void... params) {
            newlist = new ArrayList<HashMap<String, String>>();
             json = jsonParser.makeHttpRequest(json, "POST");
            try {
                newarray = new JSONArray(json);
                    for (int i = 0; i < countdisplay; i++) {
                        HashMap<String, String> eachnew = new HashMap<String, String>();
                        newobject = newarray.getJSONObject(i);
                        eachnew.put("id", newobject.getString("ID"));
                        eachnew.put("name", newobject.getString("Name"));
                        newlist.add(eachnew);
                    }
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            newlisttemp.addAll(newlist);
            NewAdapterpager newadapterpager = new NewAdapterpager(ProcesssActivitypager.this,newlisttemp);
            newpager.setAdapter(newadapterpager);
        }
    }

@Oded Breiner 2014-06-12 11:17:03

Shortest example for just doing something asynchronously:

class MyAsyncTask extends android.os.AsyncTask {
    @Override
    protected Object doInBackground(Object[] objects) {
        //do something asynchronously
        return null;
    }
}

To run it:

(new MyAsyncTask()).execute();

@Ganesh Katikar 2014-01-23 11:20:21

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute()
  2. doInBackground(Params...)
  3. onProgressUpdate(Progress...)
  4. onPostExecute(Result)

Below is an demo example

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

and once you created, a task is executed very simply:

 new DownloadFilesTask().execute(url1, url2, url3);

I hope this will help you...

@user2362956 2017-07-13 11:23:06

execute expects a paremeter as Runnable. It doesn't accept string. What is the type of your url? string or not

@Ted Hopp 2012-03-12 17:16:50

Move these two lines:

TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");

out of your AsyncTask's doInBackground method and put them in the onPostExecute method. Your AsyncTask should look something like this:

private class LongOperation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            Thread.sleep(5000); // no need for a loop
        } catch (InterruptedException e) {
            Log.e("LongOperation", "Interrupted", e);
            return "Interrupted";
        }
        return "Executed";
    }      

    @Override
    protected void onPostExecute(String result) {               
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText(result);
    }
}

@Dipen 2015-01-21 16:31:37

Hey what i am running async task on service i want to return some value to main ui thread.

@Ted Hopp 2015-01-21 20:25:05

@Dipen - Check out this discussion. There are two issues: reporting results from an AsyncTask, which my answer addresses; and sending a value from a service to the ui thread, which the other discussion addresses. These issues are independent.

Related Questions

Sponsored Content

87 Answered Questions

[SOLVED] Close/hide the Android Soft Keyboard

26 Answered Questions

28 Answered Questions

[SOLVED] What is 'Context' on Android?

41 Answered Questions

[SOLVED] Is there a unique Android device ID?

13 Answered Questions

[SOLVED] Proper use cases for Android UserManager.isUserAGoat()?

25 Answered Questions

[SOLVED] Is there a way to run Python on Android?

12 Answered Questions

77 Answered Questions

17 Answered Questions

[SOLVED] "Debug certificate expired" error in Eclipse Android plugins

1 Answered Questions

Sponsored Content