I\'ve a database that I will populate with items after I parse a JSON response. How can I check if the values are already present in the database and prevent inserting again
In your example table:
When you create your table you can set your name as unique (if that is what you want unique) with the following (Using a SQLiteOpenHelper
).
String createPlayerTable = "create table " +
TIME_REPORT +
" (" +
USER_ID + " integer primary key autoincrement not null," +
CLIENT_NAME + " text not null," +
"UNIQUE("+CLIENT_NAME+")"+
");";
Then in you insert insertIntoDatabase
method use
db.insertOrThrow(TIME_REPORT, null, initialValues);
instead of
db.insert(TIME_REPORT, null, initialValues);
This may throw a SQLiteConstraintException
so you will have add a try/catch.
Hope this is what you need.
1 )if your looking for the unique id than make your id field as auto increment and insert only name value
2 ) if you are not looking for unique than retrieve the all data for this table store in the array than compare your inserted value with existing value in data base
Create an object that will hold your data, eg. ClientData
Create a method for fetching all data from the database
public List<ClientData> selectAll() {
List<ClientData> list = new ArrayList<ClientData>();
Cursor cursor = this.myDataBase.query(TABLE_NAME, new String[] { "userID, clientName" },
null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
list.add(new ClientData(cursor.getString(0), cursor.getString(1)));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
Before executing your insert statements, fetch all data and then check if data exists:
if (!list.contains(clientData)) {
executeInsert();
}
I am not sure if SQLite supports stored procedures, but if it does, you could write a stored procedure for that as well.