Janeks Bergs Janeks Bergs - 16 days ago 5
Android Question

Activity's local variable still valid after OnDestroy()

I have declared a class for doing work in the background:

public class ReportLoadTask extends AsyncTask<Void,Void, ReportLoadTaskResult> {

public ReportLoadTask(Context context, String barcode, ReportLoadTaskListener l) {
...
}

}


I am using an instance of this class as an
Activity
's local variable:

private ReportLoadTask mReportLoadTask;

...


in one point of class' code I am preparing a task and then letting user decide whether to continue or not by showing
AlertDialog
:

mReportLoadTask = new ReportLoadTask(this, barcode, this)

...

new AlertDialog.Builder(this)
.setMessage("Continue with search?" )
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mReportLoadTask.execute();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mReportLoadTask = null;
return;
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();


When testing I was expecting
mReportLoadTask
to become
null
if I destroy
Activity
(for example by rotating the device) while
AlertDialog
is being shown. But in practice this doesn't happen. All the
Activity
lifecycle methods (
OnPause
,
OnStop
,
OnDestroy
) are being called correctly, even other local variables (some
int
s) are destroyed but this variable somehow seems to "survive". Why is that?

After exploring the Net it seems like Android is keeping a reference of this object somewhere but where could it keep it? The only reference to this object is in my
Activity
and it is being destroyed.

Answer

If you are rotating the device while dialog is being show, it means that you task is not executed (you haven't called execute yet). When you rotate the device, you activity is destroyed and recreated (it will be started from the scratch and life cycle callbacks will be called again).

When activity is recreated mReportLoadTask = new ReportLoadTask(this, barcode, this) is called again and your are getting a new instance.

Comments