How to swap an exist couchbase lite db with the new one?


In our app there is a predefined db, so after the first opening users download it, unzip it and keep using the app without problem, however sometimes the db may need to be swapped with the new one. Again users download the new db, unzip it but as expected the app does not aware of the latest downloaded until the app gets restarted because it keeps running through the memory.

In order to run by the latest db without restarting the app, we delete the exist db before unzipping the latest db like below

priceDatabase = null;

sometimes it fires exception saying “SQLiteDatabaseCorruptException: database disk image is malformed (code 11)” and everything gets corrupted suddenly.

So here is my question, how do I swap an exist db with the new one not requiring to restart the app? Deleting seems resolve the restarting problem however the db gets broken after deletion and can not unzip the new one properly.

UPDATE 1: I tried to use replaceDatabase method, it seems copy the source folder as destination but nothing changes.

UPDATE 2: reopening the db having finished unzipping seems solve

@Override public Observable<Boolean> unzip(DatabaseType databaseType) {
return Observable.create((Observable.OnSubscribe<Boolean>) subscriber -> {
  try {

  priceDatabase = null;

    Timber.d("%s unzipping is finished successfully", fileUtil.getProductDatabaseName());

  } catch (Exception e) {

As long as you close the database before replacing the directory, it should work fine. (In your code you’re closing it afterwards … that’s a very bad idea, and may corrupt the database file.)

If you were getting SQLite errors, it’s probably because you had another instance of the database open (on another thread?) that didn’t get closed.

@mustafaguven just to be clear, your second update says you solved the issue? Did you close the db before unzipping?

I want to clarify the solution and raise the visibility so it’s more obvious this got resolved.


yes hod, even though I’ve just seen jens warning I solved it d0ing what i mentioned before up here. It runs without problem, there are no any warnings, errors or corruptions. However I’m gonna refactor it as jens say. closing the db before replacing sounds both simple and effective. :slight_smile:

1 Like