I have used AsyncTasks
with my application, in order to lazy download and update the UI.
For now my AsyncTasks
updates the UI real simply:
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
gender.setText(values[0]);
}
My problem is how to check if the activity which the gender TextView
rendered from, is still available?
If not, I will get an error and my application will shut down.
Use getStatus() to get the status of your AsyncTask . If status is AsyncTask. Status. RUNNING then your task is running.
If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.
This class was deprecated in API level 30.AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
AsynTaskExample mAsyncTask = new AsyncTaskExample(); mAsyncTask. cancel(true);
You can cancel your asynctask in the activity's onDestroy
@Override
protected void onDestroy() {
asynctask.cancel(true);
super.onDestroy();
}
and when performing changes you check whether your asynctask has been cancelled(activity destroyed) or not
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if(!isCancelled()) {
gender.setText(values[0]);
}
}
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
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