2

I want to backup my application db on sdcard and later import it. The .sqlite db is managed by ORMLite. I have read the answer https://stackoverflow.com/a/20143148/335105 but following that approach will erase all the data in current db generated after the export.

Is there a way i can export my db to sdcard and later import it without loosing the already contained data? Suggestions?

Community
  • 1
  • 1
John x
  • 4,031
  • 8
  • 42
  • 67
  • 1
    had to develop a manual import/export system over the existing application and that was not pretty... sigh!!! – John x Jan 25 '15 at 14:23

1 Answers1

1

If you know that your data model will not be changed later, you can create just "dumb" export of your database. DB is stored as a file in

public static final String CURRENT_DATABASE_PATH = "data/data/" + App.getContext().getPackageName() + "/databases/" + DatabaseHelper.DATABASE_NAME

where DATABASE_NAME is your name used when creating DB.

Here are the methods I use (I'm not an author, this code is strongly inspirated by some other stackoverflow thread which I can't find right now) Export:

public static void exportDB() {
    try {
        File dbFile = new File(CURRENT_DATABASE_PATH);
        FileInputStream fis = new FileInputStream(dbFile);
        getExportDirectory(); 
        String outFileName = createExportName();
        OutputStream output = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        output.flush();
        output.close();
        fis.close();
    } catch (Exception e) {
        App.log(e);
    }
}

And again for import

public static boolean importDB(String dbPath) {
        try {
            AppStorage.get().close();
            File newDb = new File(dbPath);
            File oldDb = new File(CURRENT_DATABASE_PATH);
            if (newDb.exists()) {
                copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
                AppStorage.get().getWritableDatabase().close();
            }
            AppStorage.reset();
            return true;
        } catch (Exception e) {
            App.log(e);
        }
        return false;
    }

However, if you plan to update your data model this approach would not work, so you'll probably need to manualy export/import everything you want to.

Edit: AppStorage is my custom db wrapper. This approach won't delete your database.

vanomart
  • 1,739
  • 1
  • 18
  • 39
  • In this case, App is a class that extends Application framework class. I hold a static reference to general context in the class App, so it's always available in the app (accessible by getContext() method) – vanomart Aug 05 '16 at 13:09