Backup/restore sqlite db in android-ThrowExceptions

Exception or error:

Possible Duplicate:
Android backup/restore: how to backup an internal database?

I am developing an app in which there is SQL lite db. I need to give the user the ability to back up the database and restore it again. How can I do that? Sample code?

And in case my user saved the db, and then upgraded the app to a new DB version code, will restore work? How do I go about that?

How to solve:

In the folder “/data/data/’’/databases/” you have a .db file that is your database. You can copy that file, save it, and then place it back there again.

One example on how to backup the database to the external storage:

    final String inFileName = "/data/data/<>/databases/foo.db";
    File dbFile = new File(inFileName);
    FileInputStream fis = new FileInputStream(dbFile);

    String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";

    // Open the empty db as the output stream
    OutputStream output = new FileOutputStream(outFileName);

    // Transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length =>0){
        output.write(buffer, 0, length);

    // Close the streams


Can you clarify what you mean by “back up”? SQLite doesn’t have a specific backup method; you have to read rows from the db and save them somehow. Many developers use XML to do this.

If the user saves the db and you then move to a new DB version code, you have to decide how you’ll do the restore. Again, you have to do the work to read the backup and put it back into the database; neither SQLite nor Android does this for you.

The package contains classes for working with the Android Backup Agent, but they implement a general framework. It’s up to you to implement the specifics for each file or database you’re backing up.

Leave a Reply

Your email address will not be published. Required fields are marked *