Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-create database when using Content Providers

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?

like image 724
Programmer001 Avatar asked Nov 25 '16 00:11

Programmer001


1 Answers

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.

like image 51
Code-Apprentice Avatar answered Nov 15 '22 01:11

Code-Apprentice