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

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


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.


try {    File sd = Environment.getExternalStorageDirectory();    File data = Environment.getDataDirectory();    if (sd.canWrite()) {        String currentDBPath = "//data//"+ packageName +"//databases//"+dbList[0];        String backupDBPath = dbList[0];        File currentDB = new File(data, currentDBPath);        File backupDB = new File(sd, backupDBPath);        FileChannel src = new FileInputStream(currentDB).getChannel();        FileChannel dst = new FileOutputStream(backupDB).getChannel();        dst.transferFrom(src, 0, src.size());        src.close();        dst.close();        Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();    }} catch (Exception e) {    Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();}

That works as opposed to the above examples in which the "/" are "\" wasted 20 minutes of my life figuring that out, but I really should have seen that sooner. The Toast will tell you where the file has been place or tell you what's wrong when it doesn't work.


SQLite databases are completely self-contained files and are portable — you can just copy the entire file straight to the SD card.

Though first I'd check whether an SD card is installed in the device, and what its path is (using Environment.getExternalStorageDirectory()).