androidandroid-sqliteandroid-assetsandroid-studio-2.2

Rewritting a SQLite database in assets on build


I am making an android app mostly for my personal use. It comes together with SQLite database for storing data. In android studio I put the database is src/main/assets/ folder and I wrote a Java method for copying it in order to use it internally by the phone as indicated on a tutorial:

private void copyDatabase(File dbFile) throws IOException {
        InputStream is = context.getAssets().open(DB_NAME);
        OutputStream os = new FileOutputStream(dbFile);

        byte[] buffer = new byte[1024];
        while (is.read(buffer) > 0) {
            os.write(buffer);
        }

        os.flush();
        os.close();
        is.close();
    } 

I then copy that database by applying the method on context "this" and use it. I am currently using an emulator on Windows to debug my application and every time I make changes to the database in the assets folder, they don't get deployed correctly on the virtual phone. I have to wipe the memory of the phone clean and install the app again. Sometimes that database doesn't even get deployed properly and its tables are missing, which worries me a bit concerning potential updates: Given that I do not understand much how the compiler deploys files in resources, I would like some help with clarifying what the potential issue there could be. Is there perhaps any kind of instruction to force the debugger to rewrite all the files in assets every time on compilation?


Solution

  • Is there perhaps any kind of instruction to force the debugger to rewrite all the files in assets every time on compilation?

    It does that automatically.

    However, it will not cause your code in your question to run again automatically. Somewhere, you have code that decides when to call copyDatabase(). Probably it does not do that every time the app runs, but only if there is not already a copy of the database.

    I have to wipe the memory of the phone clean and install the app again

    If my guess from above is correct, clearing the app's data would get rid of the existing copy of the old asset, and would cause your code to call copyDatabase() again and copy out the new asset.