android数据库onupgrade,Android Studio SQLite onUpgrade

李胡媚
2023-12-01

Hi I'm currently working on a language dictionary app. The database is from SQLite db which I input manually. The feature of the app is users can ask any words that is not on the list to be added, so I have to update the database manually everytime app updated.

The problem is, everytime I change the db data, the list is not updated, when I change the version number, the app crashed.

How can I handle this problem? Tutorials out there only showing how to do it on realtime input or adding columns while main only to add rows and on already existing db. Thank you.

Here is my DataBaseHelper class

public class DataBaseHelper extends SQLiteAssetHelper {

private static final String DB_Name = "kamus_db";

private static final int DB_VER = 1;

private static final String TB_DATA = "tb_data";

private static final String COL_ID = "_id";

private static final String COL_TURKI = "turki";

private static final String COL_ISTILAH ="istilah";

private static final String COL_INDONESIA = "indonesia";

private static DataBaseHelper dbInstance;

private static SQLiteDatabase db;

private DataBaseHelper(Context ctx) {

super(ctx, DB_Name, null, DB_VER);

}

static DataBaseHelper getInstance(Context ctx) {

if (dbInstance == null) {

dbInstance = new DataBaseHelper(ctx);

db = dbInstance.getWritableDatabase();

} return dbInstance;

}

@Override

public synchronized void close() {

super.close();

if (dbInstance != null) {

dbInstance.close();

}

}

List getAllKamus() {

List kamusList = new ArrayList<>();

Cursor cursor = db.query(TB_DATA, new String[] {

COL_ID, COL_TURKI, COL_ISTILAH, COL_INDONESIA

}, null, null, null, null, null);

if (cursor.getCount() >= 1 ) {

cursor.moveToFirst();

do {

Kamus kamus = new Kamus();

kamus.setTurki(cursor.getString(cursor.getColumnIndexOrThrow(COL_TURKI)));

kamus.setIstilah(cursor.getString(cursor.getColumnIndexOrThrow(COL_ISTILAH)));

kamus.setIndonesia(cursor.getString(cursor.getColumnIndexOrThrow(COL_INDONESIA)));

kamusList.add(kamus);

} while (cursor.moveToNext());

} return kamusList;

}

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

String TAG = "TAG";

Log.w(TAG, "Upgrading database. Existing contents will be lost. ["

+ oldVersion + "] -> [" + newVersion + "]");

db.execSQL("DROP TABLE " + TB_DATA);

onCreate(db);

}

}

 类似资料: