Activity OnDestroy never called?

I am using following code in my ListActivity

// a separate class in project
public class MyActivity extends ListActivity {
    // some common functions here..
}

public class SelectLocation extends MyListActivity {

    public void onCreate(Bundle savedInstance) {
        // here.....
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (adap != null) adap = null;
        if (list != null) list = null;
        System.gc();
    }
}

any one guide me why onDestroy method is not called in my code?


Solution 1:

onDestroy() is called only when system is low on resources(memory, cpu time and so on) and makes a decision to kill your activity/application or when somebody calls finish() on your activity.

So, to test your code() you can make a test button, that will call finish() on your activity.

Read more here.

Also, I believe you don't need to call all this stuff in onDestroy() until adap is not a critical resource. And even in that case android system has mechanisms to properly dispose them.

Solution 2:

There is no guarantee that your onDestroy method will be called at all.

The code that you are using in your onDestroy method is not needed at all. If destroy is called your acitivity will be removed from the stack and is free for garbage collection anyway with all the resources in it that are only referenced by the activity. Also System.gc() is supposed to be bad style. On Android the system nearly always knows when it is the best time to do a garbage collection. Most of the times an activity finishes garbage collection is triggered automatically. Just remove the whole onDestroy method. If you have problems with the overall memory of your application the problem is somewhere else.