javaandroidmemory-leaksjava-memory-leaks

Accessing data of destroyed activity means I have a memory leak?


I've created an interface which holds a reference to an interfaces instantiated from an activity.

This is the interface:

public interface Calback {
    void fun();
}

This is the activity which instantiates the calback and binds it to asincktask.

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        final TextView txt = findViewById(R.id.helloTxtv);

        txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calback call = new Calback() {
                    @Override
                    public void fun() {
                        Log.d("tag","text of destroyed activity: "+((TextView)findViewById(R.id.helloTxtv)).getText());
                    }
                };

                Worker worker = new Worker(call);            
                worker.execute();

            }
        });


    }
}

What's strange is that using that calback I can access textview even if the activity was destroyed.

This is the code from asyncktask:

public class Worker extends AsyncTask<Void, Void, Void> {

    private final Calback call;

    public Worker(Calback call) {
        this.call = call;
    }


    @Override
    protected Void doInBackground(Void... voids) {
        try {
            sleep(5000);
            Log.d("tag","done");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        call.fun();


    }
}

To ensure that the activity it's destroyed I've just rotated the screen.(But I've got the same result after starting another activity and finish the current one)

And here is the log result.

PS: I've used Android Studio 3.0


Solution

  • If you are able to access the text of the TextView after the parent Activity has been destroyed, then you have a memory leak.

    However, I'm not convinced that is what is going on here. I think it is more likely that either the activity has not been destroyed, or the activity's state was persistent and you are now looking at the state in the new (reincarnated) activity.

    Why? Because, it seems that the callback is being called via an onClick listener for the text view. And that can only occur if the specific text view is still visible. It can't be visible if it is a component of a destroyed activity.