When are the view's 'killed' and no more exist in Android ?
For example, suppose I have an asynctask and I run some network related stuff in the doInBackground()
method. Then, I need to update my UI views in the onPostExecute()
method.
Assume my doInBackground()
took a while and while it was being processed the user moved back or even pressed the home button. The task will continue because doInBackground runs on a seperate thread, however, once it is finished and onPostExecute is called to update the views, the views might not be there.
I know a way to not get into this hastle is to use a switch that gets turned on and off inside onResume and onStop and check it before updating the views in onPostExecute, but I am unsure if this is solid approach applied in the android apps ? if not, what is the suggested way ?
A view
inside an activity can be considered like any other object
within the activity class. It will stay in the memory as long as it is referenced by the some other object
. This object could be another view
or activity
. This means the view will be gone if:
1) The activity
or the parent view
remove it removeView()
from the view tree thus no one keeps a reference to it.
2) The activity
or parent view
that contain the view are destroyed/gone from the memory.
If the activity is not visible (either gone to home screen, or another activity), what happens when the views try to get accessed and modifed ? How long do they stay in the 'heap/memory/whatever', do they get garbage collected after onDestroy ? or they stay around after that ?
You can access the view, as long as your activity is available. And you can find more about that by reading the Activity Lifecycle
When you try to access a view that is gone from the memory, you will get a NullPointerException
. The simple & solid way how you can handle onPostExecute
is by checking for null before updating, example:
// inside onPostExecute
if(textView != null) {
textView.setText("Background Method Finished");
}
The advantage of this approach is:
1) You do not have to explicitly keep track of show/hide.
2) Sometimes, view is not on the screen does not mean that it gone from the memory. For example, let say your AsyncTask
finishes while your activity is paused/stopped
not destroyed
. In this case, you can still update the view, so that when the activity is resumed
the update is visible and is not lost.