How to backup & restore SqliteDatabase,SharedPreferences on SD-Card - Android

user4209438 picture user4209438 · Jan 28, 2015 · Viewed 8.5k times · Source

Hi i am developing an application in which i am storing the data to Sqlite & SharedPrefrences. I have studied from android docs they say we can do it by registering the service but i think this is only for Cloud storage where as i want to backup the data on SD card. I have also looked for FileBackHelper but it has not given any clarity.

Please tell which is the best way t implement it?

Answer

Murtaza Khursheed Hussain picture Murtaza Khursheed Hussain · Jan 28, 2015

You can copy your sqlite db to sdcard like this

private void exportDB(){
    File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
       FileChannel source=null;
       FileChannel destination=null;
       String currentDBPath = "/data/"+ "com.your.package" +"/databases/"+db_name;
       String backupDBPath = SAMPLE_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, "DB Exported!", Toast.LENGTH_LONG).show();
        } catch(IOException e) {
            e.printStackTrace();
        }
}

Shared Preferences file location mostly chosen by device manufacture, so it is not good to hard code path of any shared preferences file.