Backup in SQLite database

5

I need to back up an SQLite Android database.

Ex: I'll change the device and I need to copy the application's DB to be loaded on the other Android phone.

Is there a workable solution?

I developed an application that uses SQLite to write information, now I need to make it possible for the user to make a backup of the database in order to transfer it to another cell.

    
asked by anonymous 28.10.2014 / 15:02

2 answers

8

The solution below was extracted from a SOEN response and does what you want, even though there is plenty of scope for improvements and better portability:

Import

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

    if (sd.canWrite()) {
        String currentDBPath = "//data//" + "<nome do package>" 
            + "//databases//" + "<nome da BD>";
        String backupDBPath = "<nome ficheiro backup da BD>"; // No SDCard
        File backupDB = new File(data, currentDBPath);
        File currentDB = 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(getApplicationContext(), "Importação com sucesso!",
            Toast.LENGTH_SHORT).show();

    }
  }
  catch (Exception e) {

    Toast.makeText(getApplicationContext(), "Importação Falhou!", Toast.LENGTH_SHORT)
        .show();
  }
}

Export

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

      if (sd.canWrite()) {
          String currentDBPath = "//data//" + "<nome do package>"
              + "//databases//" + "<nome da BD>";
          String backupDBPath = "<destino>";
          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(getApplicationContext(), "Backup com sucesso!",
              Toast.LENGTH_SHORT).show();
      }
  }
  catch (Exception e) {
      Toast.makeText(getApplicationContext(), "Backup Falhou!", Toast.LENGTH_SHORT)
          .show();   
  }
}

User Response Credentials @ adefran83 this answer in SOEN.

    
30.10.2014 / 11:36
0

In the case of getApplicationContext (), it will be interesting to pass as parameter to the constructor of the class where these methods will be the Context, for it you can access getApplicationContext ().

    
13.10.2015 / 15:13