更新SQLite数据库

时间:2012-05-30 06:48:49

标签: android android-layout sqlite

当我的第一个活动加载时,数据库将在OnCreate()中创建。然后在下一个活动中,当我从表中删除几行并再次返回第一个活动时,将创建所有数据库,其中包含所有记录。我希望数据库向我显示更新的表记录,而不是执行create&再次插入表格......

2 个答案:

答案 0 :(得分:0)

我认为在第一个活动中创建/插入数据库之前,你没有检查它是否已经存在,所以每次你输入数据库重建的第一个活动。因此,在使用以下方法创建数据库之前,请检查数据库是否已存在:


使用数据库的路径在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();
}

就是你完成了:)

答案 1 :(得分:0)

如果您计划首先创建数据库并逐步修改它,可以使用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();
}