Search code examples
androidsqliteandroid-backup-service

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


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?


Solution

  • 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.