android数据库覆盖现有数据

时间:2015-06-28 11:53:15

标签: android database

我有一个数据库,它有插入,删除,更新功能数据库工作正常,我现在为数据库添加一些值。我在像我这样的启动活动中增加了价值

    foodDbHelper = new FoodDbHelper(context);
        sqLiteDatabase = foodDbHelper.getWritableDatabase();

        foodDbHelper.addInformations
                ("Paratha", "1 piece", 260, "8.99 g", "5.16 g", "2.18 g", "38.94 g");
        foodDbHelper.addInformations
                ("Chapatti", "1 Piece", 68, "0.62 g", "2.34 g", "0.26 g", "13 g");
        foodDbHelper.addInformations
                ("Alu Paratha", "1 Piece", 329, "6.16 g", "9.08 g", "3.9 g", "38.1 g");
        foodDbHelper.addInformations
                ("Vegetable Biryani", "1 Cup", 170, "0 g", "4 g", "8 g", "36 g");
        foodDbHelper.addInformations
                ("Chicken Biryani", "1 Tray", 480, "15 g", "34 g", "0 g", "51 g");

 foodDbHelper.close();

它在应用程序运行时将数据存储在数据库中。但问题是,每次我每次运行应用程序数据存储并覆盖现有数据。当我更新是从数据库中删除值并再次运行应用程序值再次存储在数据库中我想要当我删除或更新任何值。并再次启动应用程序它不会将已删除的值存储到数据库。

1 个答案:

答案 0 :(得分:2)

此代码基本上检查键INIT_DATA_INSERTED是否存储在首选项中,值为== true 此键标志确定是否插入了init数据, 如果没有,则插入数据,并将键值设置为true

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());

if (!prefs.getBoolean("INIT_DATA_INSERTED", false)) {
    Editor editor = prefs.edit();
    editor.putBoolean("INIT_DATA_INSERTED", true);
    editor.commit();

    foodDbHelper = new FoodDbHelper(context);
        sqLiteDatabase = foodDbHelper.getWritableDatabase();

        foodDbHelper.addInformations
                ("Paratha", "1 piece", 260, "8.99 g", "5.16 g", "2.18 g", "38.94 g");
        foodDbHelper.addInformations
                ("Chapatti", "1 Piece", 68, "0.62 g", "2.34 g", "0.26 g", "13 g");
        foodDbHelper.addInformations
                ("Alu Paratha", "1 Piece", 329, "6.16 g", "9.08 g", "3.9 g", "38.1 g");
        foodDbHelper.addInformations
                ("Vegetable Biryani", "1 Cup", 170, "0 g", "4 g", "8 g", "36 g");
        foodDbHelper.addInformations
                ("Chicken Biryani", "1 Tray", 480, "15 g", "34 g", "0 g", "51 g");

    foodDbHelper.close();
}