jeudi 31 mars 2016

Copy a sqlite table from assets to data/data in Android

I am making a function that provides sqlite database update. I have a database(such as demo.db) in assets folder that is copied to my data folder when I enter the Android App for the first time. However, when I have a new version for my app, I need to replace a sqlite table in the assets folder which has already been created in the data/data folder.Here is my code:

MySQLiteHelpter extends SQLiteOpenHelper:

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        for(int i = oldVersion; i <=  newVersion; i++){
            switch (i){
                case 8:
                    //delete the older table 
                    db.execSQL("drop table if exists " + DFY_BD_DISTRICT);

                    //do something.
                    //I need to copy the table from the assets folder even I have already created the database in the previous version.

                    break;
            }
        }
    }

Here is my code I use to copy my database to data/data folder for the first time:

public static void loadDB(Context context, String dbName) {
    String packName = context.getPackageName();
    String dbPath = "data/data/" + packName + "/databases";

    try {
        File e = new File(dbPath);
        if(!e.exists()) {
            e.mkdirs();
        }

        File dest = new File(e, dbName);
        if(dest.exists()) {
            return;
        }

        dest.createNewFile();
        InputStream in = context.getResources().getAssets().open(dbName);
        int size = in.available();
        byte[] buf = new byte[size];
        in.read(buf);
        in.close();
        FileOutputStream out = new FileOutputStream(dest);
        out.write(buf);
        out.close();
    } catch (Exception var10) {
        var10.printStackTrace();
    }

}

As I have searched on the Internet,I have found some question similar to mine:Android SQLite Database - Copying Table From Assets to Local App Database I am glad that if you can give me some help : )

Aucun commentaire:

Enregistrer un commentaire