AzoftCase Studies4 Steps for Avoiding Data Corruption in SQLite 3.5.9 on Android 2.1

4 Steps for Avoiding Data Corruption in SQLite 3.5.9 on Android 2.1

By Alexander Ak on October 17, 2012

When it comes to Android application development, it’s often desirable to ensure the app is compatible with older versions of the Android OS. A customer has recently asked us to make an application while keeping backward compatibility down to SDK version 2.1 (API level 7). While working on that project, we encountered a problem: the built-in SQLite version 3.5.9 had a known bug that appeared under certain conditions. Incidentally, SQLite caused the application to crash due to a "database disk image is malformed" error and the entire database was rendered unusable. We didn't find a solution for this problem on the web, so we created the following workaround after some experimenting.

So, what should you do if you’ve stumbled upon this bug? Wrap database access into a content provider. The rest of this post gives step-by-step instructions on how to implement it in your own project.

4 Steps for Avoiding Data Corruption in SQLite 3.5.9 on Android 2.1

1. Leave SQLiteOpenHelper untouched. We'll use it later.

2. Create a content provider by subclassing android.content.ContentProvider. Next, you'll need to implement several methods, namely insert, update, delete и query. The implementation is going to be simple: parse the URI and use SQLiteOpenHelper to do the real work. Our code throws a couple of exceptions: SQLiteException and NullPointerException. Make sure you catch them - they might happen if the SD card is malfunctioning or it is out of free space.

3. Add the following lines to AndroidManifest.xml:




Note the android:exported attribute. It is used to limit access to the data provider for other applications.

4. It is convenient to take the entire URI creation and access to the underlying implementation to a higher level. The content provider will be created by the platform and work as a black box from this point:

"content://" + "com.somecompany" + "someTable", contentValues);

Adding a content provider proved to be a nice workaround for the problem and we successfully completed the project. If you'd like to learn more about ContentProvider and accessing databases, is the best source of information on the subject.

VN:F [1.9.22_1171]
Rating: 5.0/5 (1 vote cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)
4 Steps for Avoiding Data Corruption in SQLite 3.5.9 on Android 2.1, 5.0 out of 5 based on 1 rating

Content created by Alexander Ak