Stack Overflow archive
4 scoreaccepted

Is it possible to use SQLiteOpenHelper to create DB in cache dir?

score
4
question views
713
license
CC BY-SA 3.0

Here is an example of creating a database in your cache directory:

java
public class CachedDatabase extends SQLiteOpenHelper {

  public CachedDatabase(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, new File(context.getCacheDir(), name).getAbsolutePath(), factory, version);
  }

  @Override public void onCreate(SQLiteDatabase db) {
    // just for testing
    db.execSQL("CREATE TABLE example (id INTEGER PRIMARY KEY AUTOINCREMENT, foo, bar, baz, qux)");
  }

  @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  }

}

All you need to do is pass the absolute path as the name parameter in the constructor.


Tested just to make sure it was created in /data/data/[package_name]/cache:

java
CachedDatabase cachedDatabase = new CachedDatabase(this, "TEST", null, 1);
SQLiteDatabase database = cachedDatabase.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("foo", "foo");
values.put("bar", "bar");
values.put("baz", 123);
values.put("qux", true);
database.insert("example", null, values);

Checking for the database:

bash
$ adb shell
$ run-as [YOUR_PACKAGE_NAME]
$ ls cache
TEST
TEST-journal

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.