SQLiteOpenHelper with Database on SD card

For certain reasons, e.g. because a database is very big, it might be necessary to put the database on the SD card instead of the internal storage of the phone. Of course, putting the database on the SD card should be carefully thought through because it adds quite a lot of complexity, e.g. by having to deal with the case that the SD card is unmounted or replaced.

Nevertheless, in cases this approach might be appropriate, it is not obvious how to configure the location of the database if you are using SQLiteOpenHelper. The solution is to overwrite the context’s openOrCreateDatabase method. This method is called by SQLiteOpenHelper when it needs to open the actual database.

E.g. you can use the following code to store the database in the applications private folder on the sdcard.

@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode,
CursorFactory factory) {
    File externalFilesDir = getExternalFilesDir(null);
    if(externalFilesDir == null) {
        return null;
    }

    File dbFile = new File(externalFilesDir, name);
    return SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY);
}

To overwrite this method, you can either inherit from ContextWrapper and then provide the wrapped context to the constructor of SQLiteOpenHelper or you can e.g. provide an own Application class with this overwritten method and then give the application context to the constructor of SQLiteHelper.