7

My Android App has a SQLite Database and a Content Provider. This Content Provider is registered in the app's AndroidManifest.xml. It is not exported, so only my app can see it.

As part of resetting the user's profile, I want to completely wipe this database and re-create it from scratch. At first I tried calling deleteDatabase() from the activity's context. This works, but only if the app is closed and reopened afterward. Otherwise it will crash when I attempt to insert rows saying the database is read-only. My understanding is the connection needs to be closed first before calling deleteDatabase(). Yet, the connection is managed by the Content Provider and shouldn't be manually closed, as far as I understand.

As an alternative, I am using the call() method from the ContentResolver to call a custom function that will delete all of the data in the tables and reset the sequence counts manually.

This works, but now I have to delete the data from each table manually and will have to keep track of any changes I make in the future.

Is there a better way to delete the entire database and have the onCreate() of my DatabaseHelper (SQLiteOpenHelper) trigger when using a ContentProvider?

Programmer001
  • 2,240
  • 2
  • 19
  • 35
  • Why do you want to recreate and not just delete all content? – Diego Torres Milano Nov 25 '16 at 01:44
  • @DiegoTorresMilano I suppose I'm just trying to quickly refresh the database to a fresh state without having to drop each table/row (hence trying to call deleteDatabase) and let the initial setup process reconfigure the new profile as it would on the first run. Currently I am deleting all rows of data, I am just curious if there was something close to calling deleteDatabase that would have worked. – Programmer001 Nov 25 '16 at 01:58
  • 1
    You should not try to delete the file while it's still opened. – CL. Nov 25 '16 at 09:33
  • Right. I was hoping there was a way to close the connection, delete the file, and restart the connection. But it doesn't look like this will work well. I could have just been overthinking it at the time :) – Programmer001 Nov 25 '16 at 22:29

1 Answers1

1

One suggestion that comes to mind is to have your custom function drop the tables and recreate them. You already have the code to create the tables in onCreate() of DatabaseHelper. Refactor this somewhere that is accessible by both DatabaseHelper and the custom method.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Right. After deleteDatabase didn't work, I started out by dropping the tables but then decided to just delete all of their rows and reset their sequence count instead of also calling onCreate. Your answer will also work. See my reply to Diego for a little more reasoning. If there aren't any other answers I can accept this as the answer. – Programmer001 Nov 25 '16 at 02:03