How to keep activity on Force Close?
I have this piece of code that's really prone to errors so I wrapped it with try{}catch statement. I don't want to go back to the previous activity, I just want it to stay on the current activity so that the user can edit whatever is wrong with them.
How do I implement this?
try{
orgi.insertOrThrow(tableName, null, values);
Toast.makeText(this, "You have successfully created a new profile!", 2).show();
gotoProfileList();
Log.e(getClass().getSimpleName(),"Successfully added to database");
}catch(SQLiteException se){
Log.e(getClass().getSimpleName(), "Database connection failed!" + se);
//Stay in this activity...
}finally{
if (orgi != null){
orgi.close();
}
}
Forget it, I was able to solve my own problem by showing up an alertDialog that tells the user about the error. Thanks anyways. :)
开发者_如何学Python try{
orgi.insertOrThrow(tableName, null, values);
Toast.makeText(this, "You have successfully created a new profile!", 2).show();
gotoProfileList();
Log.e(getClass().getSimpleName(),"Successfully added to database");
}catch(SQLiteException se){
Log.e(getClass().getSimpleName(), "Database connection failed!" + se);
displayError();
//stayInThisActivity();
}finally{
if (orgi != null){
}
public void displayError(){
AlertDialog.Builder error = new AlertDialog.Builder(this);
error.setMessage("That profile name already exists, try another one.").setCancelable(false).setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = error.create();
alert.setTitle("Error");
alert.show();
}
Force closes are caused by uncaught exceptions. You only catche the SQLiteException in your example. You need to catch other Exceptions and handle them gracefully. Now a classical cause for FCs are use of null objects and resulting NullPointerExceptions. You shouldn't catch these. Your application will be too messed up to continue correctly in many cases. You can read more here: Catch_NullPointerException
In any case, you should run the app in the emulator or on a connected phone, cause the crash and then log into the device log with DDMS or "adb logcat". See the backtrace, find the error, fix it. If your app is in the market, the market will list backtraces send by your users devices for you. If you do not (yet?) user Android Market, you can have your app remotely log stacktraces through a PHP script running on a web server with android-remote-stacktrace
BTW it is better to pass the Exception as third parameter to the Log methods instead of concatenating the second parameter to the exception (thereby implicitly calling toString()). In your example that would be:
Log.e(getClass().getSimpleName(), "Database connection failed!", se);
精彩评论