[英]Updating SQLite Database
當我的第一個活動加載時,將在OnCreate()中創建數據庫。 然后在下一個活動中,當我從表中刪除幾行並再次返回第一個活動時,將創建所有數據庫,其中包含所有記錄。 我希望數據庫向我顯示更新的表記錄,而不是再次執行創建和插入表的操作...
我認為在第一個活動中在數據庫中創建/插入值之前,您不會檢查它是否已經存在,因此,每次輸入第一個活動時,都會重建數據庫。 因此,在使用以下方法創建數據庫之前,請檢查數據庫是否已存在:
在try塊中使用數據庫路徑打開數據庫,如下所示:
try{
SQLiteDatabase dbe = SQLiteDatabase.openDatabase("/data/data/bangla.rana.fahim/databases/dictionary", null,0);
Log.d("opendb","EXIST");
dbe.close();
}
如果發生異常,則數據庫不會退出,因此請創建它:
catch(SQLiteException e){
Log.d("opendb","NOT EXIST");
SQLiteDatabase db = openOrCreateDatabase("dictionary", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS LIST(wlist varchar);");
db.execSQL("INSERT INTO LIST VALUES('খবর');");
db.execSQL("INSERT INTO LIST VALUES('কবর');"); //whatever you want
db.close();
}
就是這樣,您完成了:)
如果計划首先創建數據庫並進行增量修改,則可以使用SharedPreferences
並且在資源中的某個位置可以有一個代表應用程序版本的數字,這樣,只有增加此數字,它才會被調用。
// In your onCreate function
SharedPreferences prefs = getSharedPreferences("myoptions", Context.MODE_PRIVATE);
int resourceVersion = //Gets the new version from the resources, for example XML
int applicationVersion = prefs.getInt("APPLICATION_VERSION", 0);
if(applicationVersion < resourceVersion ) {
// Create or update your database here
SharedPreferences.Editor editor = getSharedPreferences("myoptions", Context.MODE_PRIVATE).edit();
editor.putInt("APPLICATION_VERSION", resourceVersion );
editor.commit();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.