Question

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();
Was it helpful?

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();
        }
    });

}

OTHER TIPS

I do not know what flow u use.But have an suggestion U can do it like this.

U can start database operation like this..

Intent i = new Intent(this,Databaseoperation.class); startactivity(i); ............................... this will make controls to move to databaseoperation class it performs various operations like open.close,insert delete..etc.

U can extend databasehelper in built class

and now when any problem in opening database or any stuff , finish() intent and go back to main activity...

U can make it like this..

thanks rakesh

Does createDataBase() throw the error or handle it itself? If it handles the exception itself, then it never reaches your outer block and therefore you are never going through the catch block. Make sure to have throws IOException added at the end of the method signature like this:

public void createDataBase() throws IOException {[...]}

Also, please make sure to not have any try/catch blocks catching IOException inside of createDataBase().

That way, whenever an IOException occurs, it is being delegated to your outer catch block and your dialog will appear.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top