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

DatabaseAndroidBackupSd Card

Database Problem Overview


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?

Database Solutions


Solution 1 - Database

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.

Solution 2 - Database

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.

Solution 3 - Database

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()).

Solution 4 - Database

I answered a question similar to this with a method you can place in your SQLiteOpenHelper. It is as simple as copying the db file from some kind of external storage, to the internal application storage. There is also some extra code that opens and reads the db file to make sure it is in the proper state for Android to make database calls to it.

Solution 5 - Database

public static void BackupDatabase() throws IOException
{
    boolean success =true;
    File file = null;
    file = new File(Environment.getExternalStorageDirectory() +"/M.O.L.S_Backup");

    if (file.exists())
    {
        success =true;
    }
    else
    {
        success = file.mkdir();
    }

    if (success)
    {
        String inFileName = "/data/data/com.sygic.sdk.demo/databases/MOLS_DB.s3db";
        File dbFile = new File(inFileName);
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = Environment.getExternalStorageDirectory()+"/M.O.L.S_Backup/MOLS_DB.s3db";

        // 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 = fis.read(buffer))>0) {
            output.write(buffer, 0, length);
        }

        output.flush();
        output.close();
        fis.close();
    }
}

Solution 6 - Database

You have to give the permission android.permission.WRITE_EXTERNAL_STORAGE in your application. It works fine on unrooted devices.

Solution 7 - Database

I don't know what happens if the phone is rooted or not but you should write your files to:

/Android/data/{package_name}/files/

This will work whether it's rooted or not.

Solution 8 - Database

You find your Database Name in the Database Adapter if you are new into this.

Note that you can do this for SharedPreferences too but keep in mind to change your Context.MODE_PRIVATE to Context.MODE_MULTI_PROCESS.

SharedPreferences_name should look like this = ExportSP("temp.xml");

String currentPathForSharedPreferences = "/data/"+ context.getPackageName() +"/shared_prefs/"+ SharedPreferences_name;

For export

exportDB("MyDbName");

private void exportDB(String db_name){
		
File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + 
                File.separator + "Your Backup Folder"+ 
                File.separator );
		
		  boolean success = true;
		   if (!sd.exists()) {
			   success = sd.mkdir();
		   }
		   if (success) {
		
        File data = Environment.getDataDirectory();
       FileChannel source=null;
       FileChannel destination=null;
       String currentDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
       String backupDBPath = db_name;
       File currentDB = new File(data, currentDBPath);
       File backupDB = new File(sd, backupDBPath);
       try {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
        } catch(IOException e) {
            e.printStackTrace();
        }
		   }}

For import

importDB("MyDbName");

private void importDB(String db_name){
		File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + 
                File.separator + "Your Backup Folder"+ 
                File.separator );
        File data = Environment.getDataDirectory();
       FileChannel source=null;
       FileChannel destination=null;
       String backupDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
       String currentDBPath = db_name;
       File currentDB = new File(sd, currentDBPath);
       File backupDB = new File(data, backupDBPath);
       try {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
        } catch(IOException e) {
            e.printStackTrace();
        }
}

Solution 9 - Database

@skeniver's code works for me. I just want to add the following:

Use:

String currentDbPath = getApplicationContext().getDatabasePath("{database name}");

It will give you your database path. It is better to use that instead of hardcoding the path, like:

String currentDbPath = "//data//{package name}//databases//{database name}";

Solution 10 - Database

@Override
protected void onCreate(Bundle savedInstanceState) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//"+getPackageName()+"//databases//"+DATABASE_NAME+"";
            String backupDBPath = "backup.db";
            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();
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCodeFusionMobileView Question on Stackoverflow
Solution 1 - DatabaseskeniverView Answer on Stackoverflow
Solution 2 - DatabaseRhysView Answer on Stackoverflow
Solution 3 - DatabaseChristopher OrrView Answer on Stackoverflow
Solution 4 - DatabaseAustyn MahoneyView Answer on Stackoverflow
Solution 5 - DatabaseOsama IbrahimView Answer on Stackoverflow
Solution 6 - DatabaseTushar JadhavView Answer on Stackoverflow
Solution 7 - DatabaseJMAView Answer on Stackoverflow
Solution 8 - DatabaseORYView Answer on Stackoverflow
Solution 9 - DatabaseCharles GouwsView Answer on Stackoverflow
Solution 10 - DatabaseJose JuarezView Answer on Stackoverflow