2015-11-18 32 views
2

在我的活動表單中,我在sqlite中輸入了事件,但是當我返回到此活動或再次執行此操作時再次在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(); 
    } 
+0

真的有必要每次插入相同的事件時,活動是否被創建? –

+0

不僅第一次 – user2222

+0

然後使用'SharedPreferences'來存儲,你已經插入了值。一個代碼示例是,K寫了什麼@ρяσѕρєя。 –

回答

2

如何在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 
} 
+0

謝謝...其運行像一個魅力... – user2222

+0

但它也運行,如果我想輸入新的數據 – user2222

+0

@ user2222:當你想插入數據,那麼你應該需要刪除清除SharedPreferences使用'editor.remove(insertedInDB ); editor.commit();' –

0

這是因爲您每次都輸入它,活動就會被創建。 ommit doulbe條目的解決方案是,檢查這個條目是否已經存在於數據庫中。

您可以在SharedPreferences中保存一個值,即您已經將此條目插入數據庫。你可以將SharedPreferences想象成一張表格,它非常快速便於使用。要查看它,您可以按照Android開發人員指南here

但是您應該認爲,如果確實有必要,每次創建活動時都會插入相同的條目。

相關問題