I'd like to add a feature to my Android app that automatically backs up the SQLite database to the SD card.
What's the best way to go about this? Are any examples or tutorials available?
You can add your database file in assets folder. you can add your db file in the assets folder. If it solution isn't true, should describe your problem.
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
This code works for me!
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();
}
}
} catch (Exception e) {
}
Does anyone know if this will work on non-root phones? I have only tried it on a rooted G1.
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+ packageName +"//databases//"+dbList[0];
String backupDBPath = dbList[0];
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(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
That works as opposed to the above examples in which the "/" are "\" wasted 20 minutes of my life figuring that out, but I really should have seen that sooner. The Toast
will tell you where the file has been place or tell you what's wrong when it doesn't work.
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()
).
I answered a question similar to this with a method you can place in your SQLiteOpenHelper
. It is as simple as copying the db file from some kind of external storage, to the internal application storage. There is also some extra code that opens and reads the db file to make sure it is in the proper state for Android to make database calls to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With