在我的活动表单中,我在sqlite中输入了事件,但是当我返回此活动或再次执行此活动时,再次在sqlite中输入了数据。
我检查我的数据库文件是否充满重复或相同的数据。
我如何才能防止一次又一次地输入在sqlite中输入的数据。

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);

        MySQLiteHelper db = new MySQLiteHelper(this);


        // add events in database
        db.addEvent(new CalendarEvent("Birthday", "2016-01-15", "Location-House"));
        db.addEvent(new CalendarEvent("Birthday", "2016-01-15", "Location-House"));
        db.addEvent(new CalendarEvent("Birthday", "2016-01-18", "Location House"));
        db.addEvent(new CalendarEvent("Mobile Computing", "2015-12-10", "Location- college"));
        db.addEvent(new CalendarEvent("31th December", "2015-12-31", "Party Location-House"));


        // get all books
        List<CalendarEvent> list = db.getAllEvent();
        CalendarEvent.event_calendar_arr = new ArrayList<CalendarEvent>();
        CalendarEvent.event_calendar_arr.addAll(list);

{onCreate method from main activity and addEvent method from MySqliteHelper class}

public void addEvent(CalendarEvent calendarEvent) {

        Log.d("addEvent", calendarEvent.toString());

        // get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_EVENT_NAME, calendarEvent.getEventName()); // get event_name
        values.put(KEY_EVENT_DATE, calendarEvent.getEventDate()); // get event_date
        values.put(KEY_EVENT_DESC, calendarEvent.getEventDesc()); // get event_desc

        // insert values in event table
        db.insert(EVENT_TABLE, null, values); // key/value -> keys = column names/ values = column values
        //(table, nullColumnHack, values)

        // close
        db.close();
    }

最佳答案

首次活动调用时如何在sqlite数据库中插入数据


第一次启动应用程序时,仅使用SharedPreferences执行一次数据库插入操作:

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

if(!prefs.contains("insertedInDB")){
   // insert in DB

  // create key in prefs
   SharedPreferences.Editor editor = prefs.edit();
   editor.putBoolean("insertedInDB", true);
   editor.commit();
}else{
   // no need to insert in db
}

10-07 19:14
查看更多