2

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

2
  • 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. Commented Nov 7, 2013 at 8:58
  • 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 :-) Commented Nov 7, 2013 at 9:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I overlooked the subclasses. They make the error-handling easier. And I think I'm going to go with your advice to check if my entry is unique before I insert it.
How can one check the uniqueness of the new entry? I mean for checking the uniqueness one need to search through previous records and that means we need to run an extra query per insertion. Is there any way in which we can get the source of exception that occur and pin point it to unique constraint violation. In that way we dont need to do check before insertion.
@smasher, if a column is marked UNIQUE and it is indexed, the extra search for a row with that column value is quick. It is also the easiest and most surefire way to avoid duplicates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.