Backup/Restore Sqlite Db in Android

Backup SQLite Database in Android

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

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();
}
}

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

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/restore sqlite db in android

In the folder "/data/data/'your.app.package'/databases/" you have a .db file that is your database. You can copy that file, save it, and then place it back there again.

One example on how to backup the database to the external storage:

    final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);

String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";

// 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);
}

// Close the streams
output.flush();
output.close();
fis.close();

How to restore Sqlite database after backup Android

This is the core code of a working DB restore (from if (dbfile .. in a try).

            private static final int BUFFERSZ = 32768;
private byte[] buffer = new byte[BUFFERSZ];
........
dbfile = new File(currentdbfilename);
.......
if (dbfile.delete()) {
origdeleted = true;
}

FileInputStream bkp = new FileInputStream(backupfilename);
OutputStream restore = new FileOutputStream(currentdbfilename);
copylength = 0;
while ((copylength = bkp.read(buffer)) > 0) {
restore.write(buffer, 0, copylength);
}
restore.flush();
restore.close();
restoredone = true;
bkp.close();

The main differences are that I delete the DB file and use writes rather than transfers. Later and upon a successful restore I also use the following to restart the App (might be overkill but it works for me) as you can get unpredictable results (I think parts of the original database may be accessed from memory/cached data):-

    Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );

i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
System.exit(0);

Restoring SQLite DB file

Please use this code it may help you... I have done the same with this way

For Backup

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();
Toast.makeText(getApplicationContext(), "Backup is successful to SD card", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}

For Restore

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(backupDB).getChannel();
FileChannel dst = new FileOutputStream(currentDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Database Restored successfully", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}

A little dfference between both u can see in filechannel inside if condition.

Android sqlite backup/restore without overwriting

I think the problem of restoring old data without changing (or conflicting with) the ‘newer’ data is not very hard to solve in the scenario you describe. It seems that essentially you just want to ‘add’ the old data (records) to the new database with the assumption that the old data has no logical conflict with the newer data (that is, it is semantically OK to create new records for the old data). I believe that taking care of the primary key conflicts during restoration would be the most important issue to consider.

Let’s take two cases:

1: You are using the auto generation of primary key values feature of the database (e.g., using an AUTOINCREMENT column of a SQLite table).

Let’s assume that the ‘newer’ database records might have used primary key (ROWID) values of 1 to 10 before the restoration process is started. If you have ‘older’ database records with any of those primary key values (1 to 10), you have a problem only if you want to preserve those old primary key values. To avoid that problem, don’t retain the ‘old’ primary key value of an‘old’ record – after reading the record from the ‘old’ database, just save the values of other attributes (columns) of the ‘old’ record and let the database generate a new primary key value for this ‘restored’ record. Essentially, the ‘old’ record is saved with a new primary key value. If you are concerned about maintaining a chronological order of the records after this ‘restoration’ process, I suggest you also keep a timestamp column whose value does not get changed in the process.

2: You are using an alternate mechanism (UUID, Sequence Generators, etc.) for generating primary key values:

In this case, read the ‘old’ record and before saving it in the ‘newer’ database, replace the ‘old’ primary key value with a primary key value generated with the alternate mechanism – that would, by design, guarantee the uniqueness of the primary key value of the ‘restored’ record with respect to the pre-existing ‘newer’ records.

To simplify the programming effort for this ‘restoration’ process, especially if you are dealing with multiple tables, you may use an ORM like JDXA. One of the sample apps shipped with the SDK illustrates a similar technique for transferring ‘old’ data while upgrading a database to a newer version. JDXA also offers a convenient sequence generator mechanism to easily and efficiently create unique ids that you can assign to your objects before persisting them.

How to backup/restore SQLite database on Android to Dropbox

Using the answer here, you can get a reference to your database in the form of a .db File object.

final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);

Once you have this, it's easy to read/write to a user's Dropbox using the Dropbox Sync API.

  • Backup: Use writeFromExistingFile() to write this local File to the Dropbox directory
  • Restore: Use getReadStream() to get a FileInputStream that can write to the appropriate local path where your .db file goes.


Related Topics



Leave a reply



Submit