0

I've implemented a parser that parses web-site and then i get a big object that consists of a lot of other objects and arrays and etc. What i want is i need to store all this data to SQLite database, then export the .db file.

Then i want to create an app which will work with that db file. How can i implement it in android? can i store this db-file to assets and then replace the real db file of the app with this db-file that i get from assets?

Of course i can use json or xml or whatever, but it will take a lot of time to unwrap this data for the final user of the application.

So the idea is to generate the db-file once and then store in the assets.

Jenya Kirmiza
  • 385
  • 1
  • 3
  • 12

1 Answers1

0

So i've ended up with a solution. Here is a method to get the sqlite db file from your project

public void backupDB(){
    // getDatabasePath

    final String inFileName = "/data/data/com.example.yourproject/databases/books-db";
    File dbFile = new File(inFileName);
    try {
        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();
    } catch (FileNotFoundException fileNotFoundException){
        Log.e(LOG_TAG,"fileNotFoundException");
        fileNotFoundException.printStackTrace();
    }catch (IOException ioException){
        Log.e(LOG_TAG,"ioException");
        ioException.printStackTrace();
    }

}

here is method to get it from assets to replace the db of other project, where you want to use this database instead of other.

private void copyAssets() {
    AssetManager assetManager = mContext.getAssets();
    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open("database_copy.db");
        String currentDBPath = "/data/data/com.example.somepackagename/databases/books-db";
        out = new FileOutputStream(currentDBPath);
        copyFile(in, out);
        in.close();
        out.flush();
        out.close();
    } catch(IOException e) {

        Log.e("tag", "Failed to copy asset file " , e);
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}
Jenya Kirmiza
  • 385
  • 1
  • 3
  • 12