开发者

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.cre开发者_运维问答ateDataBase();
} 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();


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

}


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.


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜