Update sqlite database which I copy from data folder (Android)

I am using this tutorial: User Database Tutorial

I copy the database from the data folder and copy it to my device (or emulator). All is correct. I see my database in DDMS perspective. But I also want to update my database sometimes, so I did:

super(context, DB_NAME, null, 2); //changed version from 1 to 2

and change the onUpgrade method:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if(newVersion > oldVersion){
        this.myContext.deleteDatabase(DB_NAME);
        try {
            this.copyDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

But after starting, I have an older version of the database on my device. How can I remove the old version of the database and copy it. DB_NAME is my database name (with the format, but not the path), and copyDataBase () is the method that copies the database to the device (and it works).

I embed all the code:

public class DataBaseHelper extends SQLiteOpenHelper{

    private static String DB_PATH = "/data/data/sitcom.quiz/databases/";

    private static String DB_NAME = "sitcoms.sqlite";

    private SQLiteDatabase myDataBase; 

    private final Context myContext;

    public DataBaseHelper(Context context) {

        super(context, DB_NAME, null, 4);
        this.myContext = context;
    }   

    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }else{

            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){
            //database does't exist yet.
        }

        if(checkDB != null){
            checkDB.close();
        }

        return checkDB != null ? true : false;
    }


    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("adas", "dasd");

        if(newVersion > oldVersion){
            String myPath = DB_PATH + DB_NAME;
            this.myContext.deleteDatabase(myPath);
            try {
                this.copyDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}

and my activity:

DataBaseHelper myDbHelper = new DataBaseHelper(this);
        myDbHelper = new DataBaseHelper(this);

        try {
            myDbHelper.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }
        try {
            myDbHelper.openDataBase();
        }catch(SQLException sqle){
            throw sqle;
        }

Thank you if you can give me a reason or just a hint why this is not working.

+5
6

android db, onUpgrade(). , . . , , db .

+5

... , .

public void onUpgrade(SQLiteDatabase database, int oldVersion,
        int newVersion) {
    Log.w(DatabaseHelper.class.getName(),
            "Upgrading database from version " + oldVersion  + " to "
                    + newVersion + ", which will destroy all old data");
    database.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
    onCreate(database);
}
+2

, 0. setVersion(int version) . db , getVersion() . onUpgrade, .. db evrsion noe, , setVersion(int new dbVersion).

+1

Db DB.

    if(dbExist){
                Log.v("com.db","db exists");
                myContext.deleteDatabase(DB_NAME);`enter code here`
                //openDataBase();
                //do nothing - database already exist
            }else{
                Log.v("com.db","dbnot exists");
                //By calling this method and empty database will be created into the default system path
                   //of your application so we are gonna be able to overwrite that database with our database.
                this.getReadableDatabase();
}
0

:

createDataBase() :

this.getReadableDatabase();

, , , . , , . . , , , getReadableDatabase() , . , , , .

, , :

SQLiteDatabase db = this.getReadableDatabase();
if (db.isOpen()){
    db.close();
}

Even if the database is open on the check, it closes after that, and this will not give you more problems.

0
source

The basic idea is that you should use SharedPreferences to store your version of the database whenever you create a new database.
After that, when you create the database, you should check if the database has a new version, then you delete the old database and create a new one. This code works with me

private static class DatabaseHelper extends SQLiteOpenHelper {

        private static final String DATABASE_NAME = "database.name";
        private static final int DATABASE_VERSION = 1;
        private static final String KEY_DB_VER = "database_version";
        private final Context mContext;

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            mContext = context;
            initialize();
        }

        /**
         * Initializes database. Creates database if doesn't exist.
         */
        private void initialize() {
            if (databaseExists()) {
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(mContext);
                int dbVersion = prefs.getInt(KEY_DB_VER, 1);
                //
                if (DATABASE_VERSION != dbVersion) {
                    File dbFile = mContext.getDatabasePath(DATABASE_NAME);
                    // delete the old databse   
                    if (!dbFile.delete()) {
                        Log.w(TAG, "Unable to update database");
                    }
                }
            }
            // create database if needed
            if (!databaseExists()) {
                createDatabase();
            }
        }

        /**
         * Returns true if database file exists, false otherwise.
         * @return
         */
        private boolean databaseExists() {
            File dbFile = mContext.getDatabasePath(DATABASE_NAME);
            return dbFile.exists();
        }

        public void createDataBase() throws IOException {
            // If database not exists copy it from the assets
            boolean mDataBaseExist = databaseExists();

            if (!mDataBaseExist) {
                this.getReadableDatabase();
                this.close();
                try {
                    // Copy the database from assests
                    copyDataBase();

                    //**save the database version by SharedPreferences**

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(mContext);
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(KEY_DB_VER, DATABASE_VERSION);
                    editor.commit();

                    Log.e(TAG, "createDatabase database created");

                } catch (IOException mIOException) {
                    throw new Error("ErrorCopyingDataBase");
                }
            }
        }

        // Copy the database from assets
        private void copyDataBase() throws IOException {
            Log.i("TAG", "copy database");
            InputStream mInput = mContext.getAssets().open(DB_NAME);
            String outFileName = DB_PATH + DB_NAME;
            OutputStream mOutput = new FileOutputStream(outFileName);
            byte[] mBuffer = new byte[1024];
            int mLength;
            while ((mLength = mInput.read(mBuffer)) > 0) {
                mOutput.write(mBuffer, 0, mLength);
            }
            mOutput.flush();
            mOutput.close();
            mInput.close();
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,
                int newVersion) {
        }
    }
0
source

All Articles