Reputation: 23
In my activity form where i entered events in sqlite but when i returned to this activity or again execute this activity again data entered in sqlite. I check my DB file is full of duplicate or same data. How can i prevent to entering data entered in sqlite again and again.
@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();
}
Upvotes: 2
Views: 685
Reputation: 1124
This is because you are entering it every time, the activity is created. The solution to ommit doulbe entries would be, to check wether this entry already exists in the database.
You could save in SharedPreferences
a value, that you already inserted this entries to the database. You can imagine SharedPreferences
like a table, which is very quick accessable and easy to use. To check it out, you could follow the Android Developer Guide here.
But you should think, if it is really necessary, that everytime the activity is created the same entries get inserted.
Upvotes: 0
Reputation: 132982
how to data insert in sqlite database when first time activity call
Use SharedPreferences
for executing database insert operation only once when application is launched first time:
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
}
Upvotes: 2