这是我的代码:
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contactList.add(contact);
} while (cursor.moveToNext());
}
return contactList;
}
我想要的是将所有联系人与一个字符串进行比较,如果它们不匹配,则将该联系人添加到我的数据库中。这里的问题是,如果我添加下面的代码部分,是它检查单个字符串是否匹配,如果不匹配则会添加。我可以说代码是错误的,但我无法修复它。
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
if (!(cn.getName().contains(substring))) {
// Inserting Contacts
db.addContact(new Contact(record.get("9"), getDateTime()));
}
}
答案 0 :(得分:2)
List<Contact> contacts = db.getAllContacts();
boolean shouldAddToDB = true;
for (Contact cn : contacts) {
if ((cn.getName().contains(substring))) {
shouldAddToDB = false;
break;
}
}
if (shouldAddToDB) {
// Inserting Contacts
db.addContact(new Contact(record.get("9"), getDateTime()));
}