When Android opens an SQLite file, and the file is corrupt, Android deletes the file.
As surprising as it may sound, this behavior is implemented clearly in the Android source code, leading to consternation and to this Android issue.
Anyway, as app developers we just have to deal with it. What is the best strategy when opening an SQLite file?
- Corrupt files are actually often recoverable, so we can’t afford to take any risk of losing one of those corrupt files.
- Creating a backup before opening is very time-costly, and would make the app startup really slow, so anything smarter would be greatly appreciated.
The issue has been fixed starting from API level 11. Now there exists an interface: DatabaseErrorHandler which you can implement to define your own onCorruption() method. At the opening of your database you can pass this DatabaseErrorHandler as a parameter to the constructor of SQLiteOpenHelper.
e.g.
For Systems with an API level below 11 and for those who dont want to use this approach there are several alternatives.
1. Android data backup
Android offers a backup service which automatically copys the application data to a remote ‘cloud’ storage. If a database gets corrupted or the application is reinstalled after factory reset. The application data can be restored from the remote data.
For further information see: http://developer.android.com/guide/topics/data/backup.html
2. JDBC (sqldroid)
One approach could be implementing your own database connector, either native JDBC or with the sqldroid library. It is officially not supported by google and you cannot be sure whether it will be still available in future Android versions.
3. Berkley DB Java Edition
An interesting approach, also with a look to performance handling large data amounts, is the Berkley DB Java Edition.
Here is a tutorial how to use it in Android: http://download.oracle.com/docs/cd/E17277_02/html/HOWTO-Android.html
4. Customizing the android libraries
Another more risky approach is to implement your own database class by copying or extending the SQLiteDatabase.java from the android source and reimplement or override the critical parts which are:
and:
The dangerous part about that is, that you also would have to reimplement the helper classes that access the SQLiteDatabase such as
SQLiteOpenHelper. Since theSQLiteDatabaseclass uses factory methods you could face unexpected side effects.