Search code examples
androidterminateandroid-alertdialog

What is the best way to stop an activity and alert the user?


I have an application that must create a database and if that fails, then no sense moving forward. I've built an AlertDialog and show() it, but it never displays. The logic falls through and then barfs because of the missing database.

What is the right/best way to throw up a message and halt the activity? The code below executes fine (meaning the show() occurs while debugging and it falls to the next line), but the UI never displays this alert. BTW - I realize the throw might not be the most graceful but I'm not even getting that far so... B^).

try {

    myDBHelp.createDataBase();
} catch (IOException ioe) {
    new AlertDialog.Builder(this).setCancelable(false)
        .setMessage(ioe.getMessage())
        .setTitle("Database Create Failed")
        .setPositiveButton("Quit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                throw new Error("Unable to create database - please try uninstall/reinstall");
            }
         })
         .show();

Solution

  • I ususally do something like this:

    void myFunction() {
    
        try {
            somecode..
        } catch (IOException e){
            e.printStackTrace();
            doToast("Unknown Error");  //Display Toast to user
            return;           //Leave myFunction
        }
    
        somecode...  //If no error continue here
    
        return;
    }
    
    protected void doToast(final String str) {
        this.runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(myClass.this, str, Toast.LENGTH_SHORT).show();
            }
        });
    
    }