Reputation: 151
i have a list with some items.The use can save some of them in a database,as favorites.My problem is that i m getting duplicated records in the database if he try to add the same item two times in the favorites.How can i fix it?
i was thinking something like
ourDatabase.rawQuery("DELETE FROM "+DBHelper.DATABASE_TABLE+" WHERE"+DBHelper.NAME+" EQUALS "+DBHelper.NAME+");",null);
but it's not working.
This is my create Entry method
public void createEntry(String name, String dodes) {
try {
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(DODES, dodes);
// ourDatabase.rawQuery("DELETE FROM "+DBHelper.DATABASE_TABLE+" WHERE "+DBHelper.NAME+" = "+DBHelper.NAME+");",null);
ourDatabase.insert("DB", null, cv);
} catch (Exception e) {
Log.e("Exception in insert :", e.toString());
e.printStackTrace();
}
}
Upvotes: 1
Views: 875
Reputation: 5085
Before inserting, check to see if an item with the same name already exists. If so, do an update instead of an insert.
Cursor crsr = null;
try
{
crsr = ourDatabase.rawQuery("SELECT _id FROM "+DBHelper.DATABASE_TABLE
+" WHERE "+DBHelper.NAME+"='"+name+"'", null);
}
catch ( Exception excp )
{
crsr = null;
}
if ( (crsr == null) || (crsr.getCount() < 1) )
// Insert item
else
// Update item
Upvotes: 0
Reputation: 16834
The simple answer is to ensure that the record is "unique".
You can do this inside the database by adding a "unique index".
We want something like
CREATE UNIQUE INDEX unique_name ON some_table(name)
So something like this in code;
"CREATE UNIQUE INDEX unique_name ON "+
DBHelper.DATABASE_TABLE+
"("+DBHelper.NAME+")"
This means that if you try and insert a duplicate, you will get an error.
Therefore you'll also need to add code that checks whether the name
already exists, before you try and do it.
Upvotes: 3