如何检查数据库android中是否存在联系人

时间:2012-12-02 15:50:48

标签: android android-contentprovider android-sqlite

我如何检查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

                }

1 个答案:

答案 0 :(得分: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.
}

希望它有所帮助...