In your SQLiteHelper class, the DATABASE_VERSION variable should be the last. Suppose earlier DATABASE_VERSION was 1, and as it updates, it should be 2.
DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); }
Now upgrade the version of the old database to the new version. If you do not set the latest version number in the database, then onUpgrade (..., ...) will be called again.
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { logger.info("DBManager - :::: Upgrading database from version " + oldVersion+ " to "+ newVersion + ", which will modify some old table"); String sqlFileName = "update_version_1.sql"; int totalSQLQueries = executeSQLScript(db, sqlFileName); logger.info("DBManager - :::: Upgrading database from version - " +"Total " + totalSQLQueries +" queries executed succesfully from " +sqlFileName); if(db.getVersion() == oldVersion) { db.setVersion(newVersion); logger.info("DBManager - :::: DB Version upgraded from " +oldVersion +" to " +newVersion); } }
The change code for your database must be written inside the transaction. See the code below for an example of using a transaction to update a database: -
private int executeSQLScript(SQLiteDatabase db, String sqlFileName) { int count = 0; InputStream inputStream = null; BufferedReader bufferReader = null; try { db.beginTransaction(); inputStream = localContext.getApplicationContext().getAssets().open(sqlFileName); bufferReader = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while((inputLine = bufferReader.readLine()) != null) { if(inputLine.trim().equalsIgnoreCase("BEGIN;") || inputLine.trim().equalsIgnoreCase("END;")) { continue; } else { db.execSQL(inputLine); count = count + 1; } } db.setTransactionSuccessful(); } catch(Exception ex) { ex.printStackTrace(); } finally { if(bufferReader != null) { try { bufferReader.close(); } catch (IOException e) { e.printStackTrace(); } } if(inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } db.endTransaction(); } return count; }
source share