Refresh / reload database link in custom ContentProvider after recovery

I use ContentProvider in my application and everything works fine except for one small problem. I have a backup and restore function that backs up the database to a file on the SD card, and then these backup files can be restored to overwrite the current database. This whole process works, but ContentProvider still maintains the link / cache of the original database after restoring one of the old backup files. I can't seem to find a way to update or reload the database link in ContentProvider. I know that recovery works because I can see records in db using the SQLite editor, and when I close and open the application again, it displays the correct records.

Does anyone know how to do this? Is there a way to close and reopen a ContentProvider that I don't see?

+7
source share
4 answers

Do you maintain a reference to the actual SQLiteDatabase in your content provider (something like calling SQLiteOpenHelper.getWritableDatabase() in onCreate() and then save that link)? Or do you get a DB object from some place, as an assistant in each provider method?

As a rule, if you only keep a local reference to the helper and get the necessary instance for writing / reading in each method, then this problem should disappear. If not, maybe we can take a look at the provider code?

Hope this helps!

+6
source

If you target> = API 5, you can get a link to your ContentProvider using the ContentProviderClient and run a method specific to your implementation:

 ContentResolver resolver = context.getContentResolver(); ContentProviderClient client = resolver.acquireContentProviderClient("myAuthority"); MyContentProvider provider = (MyContentProvider) client.getLocalContentProvider(); provider.resetDatabase(); client.release(); 

Add a reset method to the ContentProvider implementation:

 public void resetDatabase() { mDatabaseHelper.close(); mDatabaseHelper = new MyDatabaseOpenHelper(context); } 
+26
source

Here is my solution.

 public class DataProvider extends ContentProvider { private DataDbHelper dbHelper; @Override public boolean onCreate() { // nothing here return true; } private DataDbHelper getDbHelper() { if (dbHelper== null) { // initialize dbHelper = new DataDbHelper(getContext()); } else if (dbHelper.getReadableDatabase().getVersion() != DataDbHelper.VERSION) { // reset dbHelper.close(); dbHelper = new DataDbHelper(getContext()); } return this.mOpenHelper; } } 

query(), insert(), update(), delete() use getDbHelper() to get SQLiteDatabase

The full code for my Android app is available here if you need more information.

+1
source

You can also just use the delete method without highlighting:

 context.getContentResolver().delete(YourProvider.CONTENT_URI, null, null); 
0
source

All Articles