Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backup/restore sqlite db in android [duplicate]

Tags:

Possible Duplicate:
Android backup/restore: how to backup an internal database?

I am developing an app in which there is SQL lite db. I need to give the user the ability to back up the database and restore it again. How can I do that? Sample code?

And in case my user saved the db, and then upgraded the app to a new DB version code, will restore work? How do I go about that?

like image 976
Snake Avatar asked Nov 21 '12 21:11

Snake


People also ask

How do I backup SQLite database on Android?

1. copy your db to sdcard 2. if reinstall, copy db back to the app. @earthw0rmjim Any approach in which I can get the original state retained without the network.

Where is SQLite database stored in Android mobile?

The Android SDK provides dedicated APIs that allow developers to use SQLite databases in their applications. The SQLite files are generally stored on the internal storage under /data/data/<packageName>/databases.


1 Answers

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(); 
like image 99
Pedro Lopes Avatar answered Oct 03 '22 14:10

Pedro Lopes