How do I backup a database file to the SD card on Android?

CodeFusionMobile picture CodeFusionMobile · Jan 3, 2010 · Viewed 77.6k times · Source

I'd like to add a feature to my Android app that automatically backs up the SQLite database to the SD card.

What's the best way to go about this? Are any examples or tutorials available?

Answer

skeniver picture skeniver · Apr 18, 2010

This code works for me!

    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//{package name}//databases//{database name}";
            String backupDBPath = "{database name}";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
    }

Does anyone know if this will work on non-root phones? I have only tried it on a rooted G1.