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

标签 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

                }

最佳答案

很简单,只要执行一个查询就可以了

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.
}

希望对你有帮助

关于android - 如何检查联系人是否存在于数据库android中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13670897/

相关文章:

android - 如何将我的 Activity 发送到后台并恢复?

android - 如何为按钮内的文本设置动画

android - 有没有办法在 Android 中未记录但允许的 ContentProvider 中列出列名?

android - 使用服务和 Singleton SQliteOpenHelper 进行数据隔离

android - 在自己创建的应用程序中播放视频时遇到错误 “an error occurred while initializing you tube player”

java - 客户端-服务器应用程序 : can't connect to java server from android mobile phone

Android - 在外部应用程序中打开 pdf

java - 需要 ContentProvider 来访问 SharedPreferences

android - Room DB升级需要编写完整的插入查询

syntax-error - Android SQLiteDatabase插入语法错误