【问题标题】:How to check if a string exists in a List如何检查列表中是否存在字符串
【发布时间】:2015-12-24 22:29:23
【问题描述】:

这是我的代码:

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()));
    }
}  

【问题讨论】:

  • 已编辑:List&lt;Contact&gt; contacts = db.getAllContacts(); 在 for 循环之外。
  • 对不起,我在发布代码时出错了,虽然我的代码中是这样的:p
  • 有什么问题? cn.getName().contains(substring) 没有按预期工作?
  • 问题是,即使没有一个联系人与列表匹配,我也希望将其添加到数据库中,但现在即使只有一个联系人与它所添加的列表不匹配
  • 看下面的答案

标签: android sqlite android-listview contacts


【解决方案1】:
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()));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    相关资源
    最近更新 更多