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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With