Search code examples
androidondestroy

Best way to close and shutdown objects in onDestroy


Inside the onDestroy method, whats the correct way to determine if an object was actually initialized before trying to close it/shut it down/etc.

For example, which is better:

protected void onDestroy()
{
    if(tts != null)
    {
        tts.shutdown();
    }

    if(dbWord != null)
    {
        dbWord.close();
    }

    super.onDestroy();
}

or this:

protected void onDestroy()
{
    if(tts instanceof  null)
    {
        tts.shutdown();
    }

    if(dbWord instanceof TextToSpeech)
    {
        dbWord.close();
    }

    super.onDestroy();
}

Solution

  • Use != instead of instanceOf to check if a variable was initialized. instanceOf performs additional type checking which you do not need in this case.