3

我如何检查 android 数据库中是否存在特定联系人以将其添加到数据库中,如果我检查联系人姓名可能存在另一个同名联系人的问题,所以任何人都可以帮助我,我的代码是:

String where = ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY+" = ? AND "+
               ContactsContract.RawContacts.ACCOUNT_TYPE + " = ? AND "+ 
               ContactsContract.RawContacts.ACCOUNT_NAME+" = ?";
String[] whereArg = new String[] {displayName, AccountType, AccountName};

Cursor SameName = cResolver.query(ContactsContract.RawContacts.CONTENT_URI, null, where, whereArg,null);

if (SameName == null || SameName.getCount() == 0) {
                    // the addContact method
                }else {

                    // do nothing, the contact is exsist

                }
4

1 回答 1

0

它很简单,只需执行一个查询即可

String query ="SELECT * FROM " + TABLE_NAME + " WHERE displayName " + " = whateverNameYouWantToCheckFor" ; 

/*To avoid confusions of different contacts having the same name, extended the search criteria, by including other fields during the query.*/

Cursor c = cResolver.rawQuery(query,null);

int duplicate = c.getCount(); // If there is a row containing the searched name then the count of the cursor will not be 0.

if(duplicate !=0)
{
  //Code to do whatever you want when the name exists already.
}
else
{
  //Code to do whatever you want when the name does not exist.
}

希望能帮助到你...

于 2015-01-09T06:13:07.297 回答