3

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?

pixel
  • 24,905
  • 36
  • 149
  • 251

3 Answers3

4

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
Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
1

You can create and open a database in a specific location, but you need to use SQLiteDatabase class (choose one of the openOrCreateDatabase methods): as you mentioned you can't create a database in a different path using the provided SQLiteOpenHelper.

You can also modify the code of the SQLiteOpenHelper to match your needs. Take the source code from the link, copy in a new class of your project and modify the getDatabaseLocked method.

You can also take inspiration from SQLiteAssetHelper.

Mimmo Grottoli
  • 5,758
  • 2
  • 17
  • 27
-1

If you are looking to clear the data in tabledb.execSQL("delete * from "+ TABLE_NAME);

you can also delete the tables db.delete("TABLE_NAME", null, null);

  • I want to delete contents (or DB) when user clears data in settings of the application. – pixel Jan 04 '16 at 13:38
  • When user clears data in settings of the application, all the app saved data like DB, sharedpreferences etc are got cleared automatically. – Geeky Singh Jan 13 '16 at 04:42