Name is Nilay Name is Nilay - 4 months ago 14
Android Question

save sqlite database android after application overwrite

My question is that I want to restore my application's sqlite database after I overwrite the same app on my device. I don't like to add settings again and again on start up of my app.

So is it possible in android to save the database somewhere from which I can again restore it ?

I have searched for more than hours on Google and SO but couldnt ind any solution.

EDIT: Its not a fixed database. So I can't store it in Assets Folder. It is editable by user but by default it should carry the last edited values(values before the app overwrite).

Answer

This method I find very helpful:

public static void movedb(File srcdb, File destdb)
{
    try 
    {
        if (Environment.getExternalStorageDirectory().canWrite()) 
        {                 
            if (srcdb.exists()) 
            {
                FileChannel src = new FileInputStream(srcdb).getChannel();
                FileChannel dst = new FileOutputStream(destdb).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();                    
            }
            else
            {
                //ERROR: "Database file references are incorrect"                    
            }
        }
        else
        {
            //ERROR: "Cannot write to file"
        }
    }
    catch (Exception e) 
    {
        //ERROR: e.getMessage()
    }
}

Then I just call

movedb(this, new File(<context>.getDatabasePath("...your DB name...")), new File("... your location ..."));

To back up, and then to restore:

movedb(this, new File("... your location ..."), new File(<context>.getDatabasePath("...your DB name...")));