How can I backup my database to the sdcard automatically in my app? And afterward, how do I restore it?
How can i backup my database to the sdcard automatically in my app?
Copy it using standard Java I/O. Make sure you don't have any open SQLiteDatabase
objects, though.
And afterwards how do i restore it?
Copy it using standard Java I/O. Make sure you don't have any open SQLiteDatabase
objects to the old database, though.
You can use getPath()
on a SQLiteDatabase
object to find out where it resides, AFAIK (haven't tried this).
CommonsWare, how do you copy it? Are there any tutorials for this? Thanks!
Here is my code:
// Local database
InputStream input = new FileInputStream(from);
// create directory for backup
File dir = new File(DB_BACKUP_PATH);
dir.mkdir();
// Path to the external backup
OutputStream output = new FileOutputStream(to);
// transfer bytes from the Input File to the Output File
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer))>0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
Here is a blog post with code showing how I have done this in the past (note that I would have made this just a "comment" since I did not take the time to include the answer here, apologies for the external link, but I don't have high enough rep to comment, apparently):