views:

367

answers:

4

How can I backup my database to the sdcard automatically in my app? And afterward, how do I restore it?

+3  A: 

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
A: 

CommonsWare, how do you copy it? Are there any tutorials for this? Thanks!

Trebak
A: 

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();
chrisonline
A: 

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):

Backing up your Android SQLite database to the SD card

Charlie Collins