How to handle SQLiteException in Android activity? - android

I am looking at how to handle exceptions in Android.
In the update() function in the sample code for the Notepad Content Provider, it calls getWriteableDatabase(), which can potentially throw an SQLiteException.
I notice that the NoteEditor Activity saveNote() function has the following code:
// Commit all of our changes to persistent storage. When the update completes
// the content provider will notify the cursor of the change, which will
// cause the UI to be updated.
try {
getContentResolver().update(mUri, values, null, null);
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage());
}
What happens if an SQLiteException occurs?. I want to be able to catch this exception in the Activity and display an appropriate message to the user (via a toast or something similar).
I thought I could do by adding an extra catch for SQLiteException. However, I read the following info in the Google docs:
"Remember that the Android system must be able to communicate the Exception across process boundaries. Android can do this for the following exceptions that may be useful in >handling query errors:
IllegalArgumentException (You may choose to throw this if your provider receives an >invalid content URI)
NullPointerException"
So I am now confused - can I catch the SQLiteException or not?

Whenever possible, you should catch the Exception in the class or component in which the Exception occurred. Use some sort of broadcast mechanism or return value semantics to report errors across processes.
It's admittedly a tricky situation. Some people say that if an SQLite (or other Exception) occurs in a ContentProvider, the provider should propagate the exception upwards instead of returning null in the Cursor. However, this generally won't work across processes! On the other hand, returning null doesn't give you a lot of information.
A limited set of Exceptions do traverse process boundaries, but SQLiteException isn't among them - still they might be useful/appropriate.

Related

Android Sqlite SQLiteAbortException does not work

My application uses some complex sql statements so I've gotten in the probably bad habit of using execsql often, even when I could/should probably use something like insert or update for simple things(below).
However, I am wondering why this is not working
String query = "UPDATE OR ABORT " + myTable + " SET " + .... column names and values + WHERE ...
try {
db.execSQL(query);
} catch (SQLiteAbortException e) {
Log.i(TAG, "error in the update");
I've tried this with data that should clearly fail (ie, there is no matching record to update) but I am not hitting the catch. Initially I had used UPDATE OR FAIL and a SQLiteConstraintException but when that was not caught I tried the SQLiteAbortException which specifically states
An exception that indicates that the SQLite program was aborted. This
can happen either through a call to ABORT in a trigger, or as the
result of using the ABORT conflict clause.
What am I missing here?
Update: just adding this for reference on INSERT/UPDATE OR ABORT/FAIL If SQLiteAbortException is not the way, how to catch an update abort/fail?
I just tried to find an explanation for that behavior in the Java source code part of Android API level 19, but the only place where SQLiteAbortException is (re-)thrown is in a static helper class named DatabaseUtils. It gets originally thrown from native code using a method in android_database_SQLiteCommon.cpp. It is thrown when SQLite returned error code 4, which is named SQLITE_ABORT and documented as:
/* Callback routine requested an abort */
I strongly assume a C callback function is meant with that. You can register callbacks with SQLite and they seem to have some level of control. So it appears to me that error code which gets translated into an SQLiteAbortException has little to do with an SQL ABORT clause. in fact, I highly doubt that that exception ever gets thrown, since I don't think that the native part of Android's SQLite database driver hooks callbacks into SQLite that abort requests.
The SQLite documentation of ABORT is also specific which kind of error code to expect:
ABORT
When an applicable constraint violation occurs, the ABORT resolution algorithm aborts
the current SQL statement with an SQLITE_CONSTRAINT error (...snip)
So according to the documentation of SQLite and what the native Android source code actually does, the SQLiteConstraintException is to be expected in that case and apparently Android's documentation of SQLiteAbortException is not entirely correct.

How to handle errors in custom AsyncTaskLoader?

I am extending AsyncTaskLoader which I use later in a Fragment through LoaderManager. Is there suggested way to handle errors which occur during async task? I would like to popup message asking user to cancel or retry when internet connection error occurs.
Only way which I can think of now is to make Loader to return null on error or wrap loaded object into another which would have status code.
What we did in our last project: Create a Wrapper that holds a generic and an excpetion like this:
public class AsyncTaskResult<T> {
private final T result;
private final Exception error;
//getter & setter
}
Catch all Exceptions in your doInBackground(...) and pack them into the result wrapper (or the result if no error). In your UI check the wrapper if it's an exception, then show according error message, otherwise populate the fields with the result.
For us it was also good practice to define what unique types of exceptions, there are (e.g. exception with a recoverable error where you only show a dialog or an app failure where you need to kick the user to the main menu) and only throw these kinds (on catching the specific in your asynctask), so you don't have to bother with hundreds of different exceptions and also abstract your error handling. You could also provide String keys with the correct I18n error message so you only have to write e.getMessage()
I've seen good results when returning a composite object that contains the payload (if any) and a status code, as you suggested. Then the Fragment that's hosting the AsyncTaskLoader can display an appropriate and informative error. This approach has the added advantage that it uses the built-in loader lifecycle.
Another option is to register a listener that your AsyncTaskLoader will notify when errors occur. The Facebook SDK has an example of using error listeners with loaders.

Intermittent NPE when inserting data into SQLite

I'm getting an NullPointerException when I insert values into to my SQLite table on Android and I don't understand why. I'm testing ContentValues and the database instance for null.
This is the insertion code:
public void insertOrIgnore(ContentValues values) {
SQLiteDatabase db = this.dbHelper.getWritableDatabase();
try {
//I added these null value checks to stop NPE, but doesn't help.
if (values != null && db != null) {
db.insertWithOnConflict(TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
} catch (SQLiteException e) {
} finally {
if (db != null) {
db.close();
}
}
}
where
public static final String TABLE = "albums";
Most of the time this code works with the data added to the database as expected. However, it sometimes and rarely generates the below error. The stack trace is from ACRA and I have not been able to isolate under what conditions this error occurs. I'm looking for pointers as to why this happens and what the conditions are. My knowledge of SQLite is beginner level.
java.lang.NullPointerException
at android.database.sqlite.SQLiteStatement.releaseAndUnlock(SQLiteStatement.java:290)
at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:96)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:2025)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1965)
at android.database.sqlite.SQLiteDatabase.beginTransaction(SQLiteDatabase.java:690)
at android.database.sqlite.SQLiteDatabase.beginTransactionNonExclusive(SQLiteDatabase.java:605)
at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:247)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1844)
at com.mydomain.myapp.albums.AlbumsData.insertOrIgnore(AlbumsData.java:89)
Line 89 is the db.insertWithOnConflict(...) call shown above.
I'm not looking for an answer with complete code necessarily but rather a pointer and explanation as to what's going wrong so I can begin to fix it myself.
EDIT:
The stack trace shows the NPE originates from line 290 of SQLiteStatement (v 4.03):
setNativeHandle(mDatabase.mNativeHandle);
So it seems the database instance is null. How can it become null during a transaction when I tested for null at the beginning of the transaction?
As mentioned here SQLiteDatabase close() function causing NullPointerException when multiple threads
The reason for your bug could be that you close the database at some point. Probably concurrently while the task that fails was not finished.
I've followed the stacktrace a bit and this is what roughly happens:
AlbumsData.insertOrIgnore(AlbumsData.java:89)
You call insertWithOnConflict, which builds the resulting sql string ("INSERT OR IGNORE INTO...") then wraps that together with the values from your ContentValues into a SQLiteStatement.
SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1844) - The resulting statement is to be executed now
SQLiteStatement.executeInsert(SQLiteStatement.java:112) - before the actual insert can happen, the database needs to acquire a lock.
SQLiteStatement.acquireAndLock(SQLiteStatement.java:247) - some checks happen here, the database object is as far as I can see not null at that point. Code decides that it has to start a transaction. The database object itself is as far as I can see not locked at that point.
SQLiteDatabase.beginTransactionNonExclusive(SQLiteDatabase.java:605) - just forwarding
SQLiteDatabase.beginTransaction(SQLiteDatabase.java:690) - after some checks (not sure if database has to exist here) it will try to execute execSQL("BEGIN IMMEDIATE;")
SQLiteDatabase.execSQL(SQLiteDatabase.java:1965) - just forward
SQLiteDatabase.executeSql(SQLiteDatabase.java:2025) - builds another SQLiteStatement out of "BEGIN IMMEDIATE;. This one should be executed now
SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:96) - starts with checking the database lock, this seems to be okay and the database should not be null here. The statement is then executed and finally the database is to be unlocked again.
SQLiteStatement.releaseAndUnlock(SQLiteStatement.java:290) - cleans up some stuff and in the end fails with NPE because the database is null.
Line numbers don't match so there are probably vendor modifications / additions in that code.
As you can see, the code crashes before actually using the data you supplied. It was about to do
BEGIN TRANSACTION IMMEDIATE; -- crash
INSERT INTO table (...) VALUES (...);
-- (end transaction)
That makes it in my opinion a framework bug. The database object that is internally handled there should not be able to be null somewhere down the line, especially when it seems that it was not null further up in the stack.
I also think that it is possible that another hidden exception could be the root cause for this. There are a lot of try { /* do stuff */ } finally { /* clean up */ } blocks within the code and the finally part will be executed even if the try part throws an exception. Now the finally block could cause another exception and the result is AFAIK that the original exception is replaced by the new exception from the finally block.
Especially executeUpdateDelete() is like
try {
acquireAndLock(WRITE);
// actual statement execution
} finally {
releaseAndUnlock();
}
if the database is closed at that point, acquireAndLock or any code in the try part could fail and that could leave the database object at null which causes releaseAndUnlock to fail again. You should get the same stacktrace.
Apart from that, don't do empty catch blocks like catch (SQLiteException e) { /* empty */ }. Log them with ACRA if possible / you don't do that already.
This NPE appears to be from a custom ROM as the Android source code is pointing to different Methods than the ones you receive in the LogCat. What I do for such cases is that: if the rate of these exceptions is very rare, I ignore them as it is difficult to know what custom ROM is running on the phone and more difficult to get the source code of this custom ROM to know where the problem is.
Not many users are using custom ROMs, so if you extensively tested your App on different phones with different SDKs and the rate of the Exceptions you get is not that significant, you can ignore them. Otherwise, you can take a shoot in the dark and speculate what can be in this custom ROM that is causing NPE (personally, I think it is not worth the effort).

Android Throw Exception

In my application, I use SQLiteOpenHelper class and it has insertOrThrow method. I want to learn that will this method close my connection before throw an exception? And it is written on definition of method that "the row ID of the newly inserted row, or -1 if an error occurred "
When throw an exception how it has a return value? Something is wrong. Explanation or throw ?
This is how I use InsertOrThrow.
I want to know when I declare throws Exception to my method, is it necessary to use try-catch (If I don't have any special thing to do in catch like my exp.)?
public long insert(ContentValues cv) throws Exception {
try
{
long rowId = getWritableDatabase().insertOrThrow(_tableName, null, cv);
return rowId;
}
catch (Exception ex) {
throw ex;
}
finally{
Close();
}
}
It depends; if this.Close() can throw an exception, then it still needs to be declared as being thrown, or caught. Often times this is wrapped up in a small utility method.
It's not mandatory to use a catch, you can simply try/finally.
Regarding return values: methods that exit due to an exception don't have a return value.
Exceptions should encapsulate enough information to either:
allow the caller to do something useful with the exception, e.g., retry the operation, or
assist the developer in understanding the problem and lead him/her to a resolution.
I'd encourage you to follow standard Java naming conventions to avoid confusing readers of your code: non-final variables should begin with a lower-case letter. Method names should also begin with lower-case letters.
Also, you do not need to preface methods (or variables) with this when there is no need to disambiguate the property you're accessing.
When throw an exception how it has a return value? Something is wrong.
Yes, you're right. The documentation seems wrong.
insertOrThrow doesn't return -1 , instead, it will throw SQLException if the query failed. There's a another method called insert which would return -1 if the query failed, and newly created rowID if success.

Android - Testing a simple Activity method

i'm writing you today because i have a real and concrete question about how testing an activity method. Let me explain the situation.
I have an activity (A) which use a method save(param) from a service (S). This method throws a specific exception if the parameter is invalid.
Unit tests are written for this part, and now, i would like to test the Activity part :
In my Activty, i use the following code to call the save() method
public void OnSaveClicked()
{
try{
if ( S.save(my_object) > 0 ) // Object Saved
{
ShowToast(this, "Your object has been saved successfully !");
}
else { // Error occured with the database
ShowToast(this, "An error occured with the database");
}
catch (MyException ex)
{
ShowToast(this, "The object you are trying to save is not valid... Please check information you entered");
}
}
The test that i'm trying to write has to check if the save() method raised the exception or not. To do that, i simulate a click on the UI Button, but, i don't really know what do i have to check. I read that's not possible to write an assert on a toast message. I'm currently thinking about using a dialog but i am not sure that the way i'm thinking is the right one. Is it normal to test that or not ?
Would you give me your feedback about that, and discuss about the right way to test activity ?
Thanks,
t00f
You might want to look at Robolectric. They have support for assertions like this http://groups.google.com/group/robolectric/browse_thread/thread/87952e620ce1bb37?pli=1
Thanks,
Ian

Categories

Resources