SQLite database on SD card

user291701 picture user291701 · Jan 26, 2011 · Viewed 28.6k times · Source

I'm looking to create a sqlite database on the sd card (don't want to use up the user's internal storage). I'm familiar with the OpenHelper pattern:

public DatabaseFoo(Context context) {
    OpenHelper openHelper = new OpenHelper(context);
    mDb = openHelper.getWritableDatabase();
}

private static class OpenHelper extends SQLiteOpenHelper {
    public OpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    ...

so if we want to create on the sd card, I think instead we have to use:

public static SQLiteDatabase openOrCreateDatabase (String path, 
      SQLiteDatabase.CursorFactory factory);

But what is the "factory" argument supposed to be, what factory should be used?

Also a bit worried about what happens if the user removes the SD card while my app is in use..

Thanks

Answer

Charlie Collins picture Charlie Collins · Jan 26, 2011

I haven't tried to do what you describe there, but presumably it could be done and might work -- with a few caveats. First, the external storage (SD card) is not secure, so any other application, or the user, could read/write to it. Second, as you noted, when it's unmounted the DB goes away.

Because of these disadvantages, you would probably be better off to try to use an internal storage database (the default), that is small and possibly includes pointers to external data (like images or files) -- that themselves can be on the external storage (and that have placeholders, or other handling, when the external storage is not available).

Still, if you want to try it, you might be better off override the getDatabasePath method of Context, such as with your own Application object, and then pass that into a regular SQLiteOpenHelper. Then you wouldn't have to worry about the cursor factory (which is optional, as the source confirms -- so just pass null if instead you want to go that route).