Close application on error

Posted by poke on Stack Overflow See other posts from Stack Overflow or by poke
Published on 2010-04-18T18:51:44Z Indexed on 2010/04/18 20:43 UTC
Read the original article Hit count: 353

Filed under:

I’m currently writing an application for the Android platform that requires a mounted SD card (or ExternalStorage). I know that it might not be the best way to require something like that, but the application will work with quite a lot of data, and I don’t even want to think about storing that on the device’s storage.

Anyway, to ensure that the application won’t run without the external storage, I do a quick check in the activity’s onCreate method. If the card is not mounted, I want to display an error message and then quit the application.

My current approach looks like this:

public void onCreate ( Bundle savedInstanceState )
{
    super.onCreate( savedInstanceState );
    setContentView( R.layout.main );

    try
    {
        // initialize data storage
        // will raise an exception if it fails, or the SD card is not mounted
        // ...
    }
    catch ( Exception e )
    {
        AlertDialog.Builder builder = new AlertDialog.Builder( this );
        builder
            .setMessage( "There was an error: " + e.getMessage() )
            .setCancelable( false )
            .setNeutralButton( "Ok.", new DialogInterface.OnClickListener()
            {
                public void onClick ( DialogInterface dialog, int which )
                {
                    MyApplication.this.finish();
                }
            } );
            AlertDialog error = builder.create();
            error.show();
            return;
    }

    // continue ...
}

When I run the application, and the exception gets raised (I raise it manually to check if everything works), the error message is displayed correctly. However when I press the button, the application closes and I get an Android error, that the application was closed unexpectedly (and I should force exit).

I read some topics before on closing an application, and I know that it maybe shouldn’t happen like that. But how should I instead prevent the application from continuing to run? How do you close the application correctly when an error occurs?

© Stack Overflow or respective owner

Related posts about android