我需要根据多列中的信息检查重复记录。如果我只使用一列来检查,我可以让它工作,但我需要它来检查三列,如果所有三列都匹配,则显示敬酒。下面的代码运行,但没有写入数据库。如果我从 if 语句中删除两个字符串,它可以正常工作并写入数据库。我曾尝试使用多个游标,但在尝试检查多个列是否有重复项时,我得到了相同的结果。
private void saveState() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
eventDate = sdf.format(calendar.getTime());
String date = eventDate;
String event = eventTitle.getText().toString();
String empID = result;
Cursor cursor = mDbHelper.fetchAllEntries();
while (cursor.moveToNext()) {
String enteredDate = cursor.getString(cursor.getColumnIndex("date"));
String enteredEvent = cursor.getString(cursor.getColumnIndex("event"));
String enteredEmpId = cursor.getString(cursor.getColumnIndex("empID"));
if ( (enteredEmpId.equals(empID)) && (enteredDate.equals("date") && (enteredEvent.equals(event)))) {
Toast.makeText(this, "Employee has already been scanned for this event.", Toast.LENGTH_LONG).show();
} else {
mDbHelper.createEntry(date, event, empID);
}
}
}
如果需要,这也是我的 Helper 类中的 fetchAllEntries() :
public Cursor fetchAllEntries() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,
KEY_EVENT, KEY_EMPID}, null, null, null, null, null);
}
编辑:我让它显示吐司,但由于某种原因它仍在写入数据库。我还注意到吐司在屏幕上停留了很长时间。我认为这是因为它在 while 循环中并且在完成之前不会关闭。我之前忘了提到,这个应用程序正在扫描条码,所以它需要能够识别它们是否已经被扫描,以了解扫描发生的日期和事件。这是更新的代码
private void saveState() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
eventDate = sdf.format(calendar.getTime());
String date = eventDate;
String event = eventTitle.getText().toString();
String empID = result;
Cursor cursor = mDbHelper.fetchAllEntries();
if (cursor.getCount() == 0) {
mDbHelper.createEntry(date, event, empID);
} else if (cursor.getCount() > 0 ) {
while (cursor.moveToNext()) {
String enteredDate = cursor.getString(cursor.getColumnIndex("date"));
String enteredEvent = cursor.getString(cursor.getColumnIndex("event"));
String enteredEmpId = cursor.getString(cursor.getColumnIndex("empID"));
if ((enteredDate.equals(date)) && (enteredEvent.equals(event)) && (enteredEmpId.equals(empID))) {
Toast.makeText(this, "Employee has already been scanned for this event.", Toast.LENGTH_SHORT).show();
} else {
mDbHelper.createEntry(date, event, empID);
}
}
}
}