Backup and Restore SQLite Database to Sdcard

Backup and restore SQLite database to sdcard

Here is my code:

    // Local database
InputStream input = new FileInputStream(from);

// create directory for backup
File dir = new File(DB_BACKUP_PATH);
dir.mkdir();

// Path to the external backup
OutputStream output = new FileOutputStream(to);

// transfer bytes from the Input File to the Output File
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer))>0) {
output.write(buffer, 0, length);
}

output.flush();
output.close();
input.close();

Restore from Room Sqlite database from sd card not working

After testing and looking around much and thanks to @MikeT i was able to use this class below for backup and restore.

public class BackupAndRestore {

public static void importDB(Context context) {
try {
File sd = Environment.getExternalStorageDirectory();
// by closing the database some other database files ending with -shm and -wal are deleted so that there is one database file and it has all content
AppDatabase.getDatabaseInstance(context).close();

if (sd.canRead()) {
File currentDB = context.getDatabasePath(AppDatabase.DATABASE_NAME);
File backupDB = new File(sd, AppDatabase.DATABASE_NAME);

transfer(context, backupDB, currentDB);
Toast.makeText(context, "Database Restored successfully", Toast.LENGTH_SHORT).show();

}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void exportDB(Context context) {
try {
File sd = Environment.getExternalStorageDirectory();
// by closing the database some other database files ending with -shm and -wal are deleted so that there is one database file and it has all content
AppDatabase.getDatabaseInstance(context).close();

if (sd.canWrite()) {
File currentDB = context.getDatabasePath(AppDatabase.DATABASE_NAME);
File backupDB = new File(sd, AppDatabase.DATABASE_NAME);
transfer(context, currentDB, backupDB);

Toast.makeText(context, "Backup is successful to SD card", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

private static void transfer(Context context, File sourceFile, File destinationFile) throws IOException {
if (sourceFile.exists()) {
FileChannel src = new FileInputStream(sourceFile).getChannel();
FileChannel dst = new FileOutputStream(destinationFile).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}

}

In my main activity I call method like below

    ...

if (item.getItemId() == R.id.backup) {
BackupAndRestore.exportDB(getBaseContext());
restartApplication();
} else if (item.getItemId() == R.id.restore) {
BackupAndRestore.importDB(getBaseContext());
restartApplication();
}

...

So the restartApplication method is called after backup because I noticed the room database was not working properly after backup unless i restart the application and also after after restoring I could not see the restored data unless the application was restarted. The restart method is below

private void restartApplication() {
finish();
startActivity(getIntent());
System.exit(0);
}


Backup SQLite database to SD card

Try adding runtime permission request for Android 6.0 (API Level 23) and above, from official docs

Code for getting WRITE_EXTERNAL_STORAGE permission

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1 && !checkIfAlreadyhavePermission()) {
requestForSpecificPermission();
}

private boolean checkIfAlreadyhavePermission() {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
return false;
}
return true;
}

Ask for permission else like this

private void requestForSpecificPermission() {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
}

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

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.

SQLite Database Backup and restore

The exception says quite clearly, that your context field is null. And that's true, because you have never assigned a value to it.

private Context context;

public NaprawyDB(Context context) {
super(context, dbName, null, DATABASE_VERSION);
this.context = context; //<--- this line is missing.
}

Backup SQLite Database in Android

Finally, with this GitHub sample I successfully implemented whatever customization I needed. And it's live now.

Android backup and restore database to and from SD-card

I always use 1.). Here's a class of mine that does backup of a DB to SD-card. I'm using FileUtils from the Apache commons-io here, you need to change that if you don't use that jar. In addition there's need for a method in your SQLiteOpenHelper class (here MySQLiteOpenHelper.getDatabaseName()) that returns the name of your database file.

You will call that from within an AsyncTask in one of your activities...

public class MyDatabaseTools {
private String appName = "";
private String packageName = "";

public boolean backup() {
boolean rc = false;

boolean writeable = isSDCardWriteable();
if (writeable) {
File file = new File(Environment.getDataDirectory() + "/data/" + packageName + "/databases/" + MySQLiteOpenHelper.getDatabaseName());

File fileBackupDir = new File(Environment.getExternalStorageDirectory(), appName + "/backup");
if (!fileBackupDir.exists()) {
fileBackupDir.mkdirs();
}

if (file.exists()) {
File fileBackup = new File(fileBackupDir, MySQLiteOpenHelper.getDatabaseName());
try {
fileBackup.createNewFile();
FileUtils.copyFile(file, fileBackup);
rc = true;
} catch (IOException ioException) {
//
} catch (Exception exception) {
//
}
}
}

return rc;
}

private boolean isSDCardWriteable() {
boolean rc = false;

String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
rc = true;
}

return rc;
}

public MyDatabaseTools(final Context context, final String appName) {
this.appName = appName;
packageName = context.getPackageName();
}
}

android - restore sqlite database from internal storge to appication

after exporting your database you can use this function to import the database, I had it testet and it works fine :

private void importDB() {
String appDataPath = getApplicationContext().getApplicationInfo().dataDir;

File dbFolder = new File(appDataPath + "/databases");//Make sure the /databases folder exists
dbFolder.mkdir();//This can be called multiple times.
//EDITED
File dbFilePath = new File(appDataPath + "/databases/"+"yourDataBaseName");

try {
//EDITED
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "YourBackupFolder","yourDataBaseFileName);
FileInputStream inputStream = new FileInputStream(file); //use your database name
OutputStream outputStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();

} catch (IOException e){
//handle

e.printStackTrace();
}
}

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

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



Related Topics



Leave a reply



Submit