Backup Android Database

I am looking for ways to back up the database of my application on an Android phone. I know that SQLite databases are just files, so I expect that you can just copy the file to the SD card, if available.

However, I am not sure how to prepare my database / activity for backup / restore.

On startup, my main action reads records from a single table in the database and displays them in a ListView . As shown in the example Notes API, I have a cursor that is automatically notified of changes to this table (the ListView automatically updated when adding / removing / updating records in the table).

So: when I copy the database file to the SD card, I should not have a problem. But what if the user wants to restore the database file? I can’t just copy the file back to the data folder, can I (EDIT: ... while the view displays data from the database and therefore may contain an open connection)?

What would be “best practice” when implementing backup / restore? One approach that I reviewed is as follows:

  • Open a special “restore” operation that does not contain an open connection database
  • Call finish() for the main activity of deleting and closing the database connection
  • Copy database file
  • Open a new "instance" of the main action.
  • The finish() call for the restore operation

Will it be the way? Thanks for any advice!

+4
source share
1 answer

But what if the user wants to restore the database file? I can’t just copy the file back to the data folder, can I?

Yes, you can. Since you can move the file from the data folder to the folder on the SD card, you can move the file from the SD card to the data folder.

What you have proposed now is a good approach, just keep in mind that you do not want to open database objects during backup / restore.

+5
source

Source: https://habr.com/ru/post/1300811/


All Articles