Reputation: 1371
As I said, is this a correct use of AsyncTask ?
I mean, without using any parameters, passing the activity context on the onPreExecute()
, and not getting the result of the doInBackground()
returned value, but the manager itself once the onPostExecute()
is called.
And one more thing, Asynctask API Reference it's said about onPostExecute()
: "This method won't be invoked if the task was cancelled." , so what about if SomeException happens while doing the doInBackground()
method, ¿Is onPostExecuted()
called?
public class MainClass {
...
//Somewhere in the class, the task is called:
new MyAsyncTask.execute();
...
private class MyAsyncTask extends AsyncTask <Void,Void,Void> {
private MyManager manager;
protected void onPreExecute(){
super.onPreExecute();
//We initialice the members here, passing the context like this:
manager = new Manager(MainClass.this);
manager.initializeMembers();
}
protected void doInBackgroud(Void ...params){
try{
//here we use the long operation task that is inside the manager:
manager.startLongTask();
} catch (SomeException e){
doWhatEverItIsWith(e);
}
return null;
}
protected void onPostExecute (Void result){
super.onPostExecute(result);
//Here we get the result from the manager
handleTheResultFromHere(manager.getResult());
}
}
}
Thank you.
Upvotes: 0
Views: 113
Reputation: 67286
As I said, is this a correct use of AsyncTask ?
Yes, its ok to pass the Activity context in onPreExecute()
and then loading the data in doInBackgroud()
and updating the UI in onPostExecute()
.
so what about if SomeException happens while doing the doInBackground() method, ¿Is onPostExecuted() called?
Yes, onPreExecute()
will be called if you get any exception in doInBackgroud()
. You have to check the data to be loaded in onPreExecute()
checking if the data is not null and update the UI.
NOTE:
Never try to update UI from doInBackgroud()
it will give you exception as you can't update UI from a non-UI thread. Alternate is to use Handler
or runOnUIThread()
for updating UI from a non-UI Thread.
Upvotes: 1
Reputation: 6141
There is no problem in using AsyncTask like this. You don't have to use doInBackground
return value. Concerning second question, yes onPostExecute
will be called even in case of exception. If you don't want to call it, you would have to use MyAsyncTask.cancel(true)
Upvotes: 1