2
votes

I'm trying to make my SQLite Database interactions in my Android code more robust.

On of my tables has one column that is marked as UNIQUE. Now I want to handle the case that my application tries to enter a non-unique entry. To achieve that I use the method SQLiteDatabase.insertOrThrow(). That method throws an android.database.sqlite.SQLiteException. Unfortunately that exception doesn't allow me to get the error code (like java.sql.SQLException kindly does). So in my catch-block I have no way of handling the exception error-code-sensitive, am I correct?

What is best practice to handle SQLiteExceptions on Android? Can my application really just say there's a problem but not find out what the problem is?

Thank you for your help and time. Dan

1
There are also other conflict handling mechanisms than throw. See e.g insertWithOnConflict(). There's no single "best practice", it depends on your particular case. Could you clarify your question to be more specific? Thanks. - laalto
Thanks for your comment laalto, my question is if there's a way to get the error-code, returned from SQLite, from SQLiteException. Roy Dictus pointed me to the subclasses like SQLiteConstraintException which basically translate to the error codes. So my question is answered :-) - dan12345

1 Answers

2
votes

What you can do in this particular case, is to verify whether the record you are about to insert will indeed be unique. That way you can avoid inserting a non-unique value and this issue is no longer an issue.

That being said, a number of specific exceptions inherit from SQLiteException, such as SQLiteConstraintException. You can also catch the specific ones and do what you must.