pardom-zz / ActiveAndroid

Active record style SQLite persistence for Android
http://www.activeandroid.com
4.7k stars 1.03k forks source link

Import and Export #560

Open deshario opened 5 years ago

deshario commented 5 years ago

How to import and export "dbname.db" ?

  1. How to export db into storage ? (I had done manually)
  2. How to import db from storage to app ? (Not idea yet)

private void exportDBNow(String foldertoSave){
        File sd = new File(foldertoSave);
        boolean success = true;
        if (!sd.exists()) {
            success = sd.mkdir();
        }
        if (success) {
            File data = Environment.getDataDirectory();
            FileChannel source=null;
            FileChannel destination=null;
            String currentDBPath = "/data/"+ SettingsActivity.getInstance().getPackageName() +"/databases/"+ "agriculture.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, "agriculture.db");
            try {
                source = new FileInputStream(currentDB).getChannel();
                destination = new FileOutputStream(backupDB).getChannel();
                destination.transferFrom(source, 0, source.size());
                source.close();
                destination.close();
                Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

** I wanna know how to import .db file into app Thankx**
15characterlimi commented 3 years ago

Even your export code above does not work reliably, because databases consist of more than one file (at least from Android Pie onwards, which enabled write-ahead logging by default). You'll have to use sqlite commands to make sure your export is aware of latest sqlite features (such as write-ahead logging). One way to safely export a database is to run sqlite3's own .dump command (i.e. run /system/bin/sqlite3 /path/to/database .dump). That command's output is SQL that will recreate the database.

Obviously, you will also need to make sure that no concurrent access on the database is happening. It's best to close the database before dumping it, and make sure the database doesn't exist before restoring it.