2

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 ints) 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.

Janeks Bergs
  • 224
  • 3
  • 13

1 Answers1

2

If you are rotating the device while dialog is being show, it means that your task is not executed (you haven't called execute yet). When you rotate the device, your 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.

mallaudin
  • 4,744
  • 3
  • 36
  • 68