Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, Singleton AsyncTask

Is there any possibility of defining a single instance of AsyncTask, rather than defining in every class ?

Or it is designed to be defined separately for each activity ?

I have 4-5 activities, each with different url to request, and for url's response, I have defined a separate class with methods to parse and populate objects as per request made.

EDIT: I made a mistake above. Actually, should I define a single class extending from AsyncTask and or define a private class inside each Activity where required ?

My apologies, I am a bit confused.

Thanks.

like image 653
user3141985 Avatar asked Mar 25 '14 08:03

user3141985


People also ask

What is AsyncTask in Android?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

How to use AsyncTask in Android Studio?

AsyncTask class is firstly executed using execute() method. In the first step AsyncTask is called onPreExecute() then onPreExecute() calls doInBackground() for background processes and then doInBackground() calls onPostExecute() method to update the UI.


2 Answers

No, because an AsyncTask can be executed only once (an exception will be thrown if a second execution is attempted). So you have to create a new instance of the AsyncTask every time you want to execute it.

like image 56
makovkastar Avatar answered Oct 19 '22 16:10

makovkastar


Hope this helps you:

public class MyAsynctask extends AsyncTask<String, Integer, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
        int i = 0;

        for (int x = 0; x < 500; x++) {
            i++;
        }
        return i;
    }

    @Override
    protected void onPostExecute(Integer result) {

        super.onPostExecute(result);
    }

}

Activity wich uses the Asynctask:

public class MyAsyncUser extends Activity{

    int result;
    TextView view;
    public void onCreate(android.os.Bundle savedInstanceState) {

        view = new TextView(this);

        new MyAsynctask(){
            protected void onPostExecute(Integer result) {
                view.setText("" + result);
            }       
        }.execute("what to do");
    }
}

So you can define a Asynctask class and use it and make something with your result in deífferent places.

like image 36
A.S. Avatar answered Oct 19 '22 15:10

A.S.