Search code examples
androidcachingsqliteopenhelper

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


I would like to create a database in cache so it could be wiped out when user clicks Clear cache button.

Clear cache in Chrome browser

In SQLiteOpenHelper constructor there is only argument to pass a name of database, not a directory (default is dadabases).

Is there any option to delete such DB when user wants to clear cache?


Solution

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

    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:

    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:

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