从联系人获取基于名称的电话号码Android

问题描述:

我正在开发一个应用程序,我需要从提供的名称对应的联系人中获取电话号码。我已经尝试了很多代码,但他们似乎都没有工作。从联系人获取基于名称的电话号码Android

这是我目前使用现在

public static String getContactPhoneNumber(Context context, String contactName, int type) { 
     String phoneNumber = null; 

     String[] whereArgs = new String[] { contactName, String.valueOf(type) }; 

     Log.d(TAG, String.valueOf(contactName)); 

     Cursor cursor = context.getContentResolver().query(
       ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
       null, 
       ContactsContract.Contacts.DISPLAY_NAME + " = ? and " 
         + ContactsContract.CommonDataKinds.Phone.TYPE + " = ?", whereArgs, null); 

     int phoneNumberIndex = cursor 
       .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER); 

     Log.d(TAG, String.valueOf(cursor.getCount())); 

     if (cursor != null) { 
      Log.v(TAG, "Cursor Not null"); 
      try { 
       if (cursor.moveToNext()) { 
        Log.v(TAG, "Moved to first"); 
        Log.v(TAG, "Cursor Moved to first and checking"); 
        phoneNumber = cursor.getString(phoneNumberIndex); 
       } 
      } finally { 
       Log.v(TAG, "In finally"); 
       cursor.close(); 
      } 
     } 

     Log.v(TAG, "Returning phone number"); 
     return phoneNumber; 
    } 

在通过联系人名称代码(比如:李四)和式(2这是移动类型为int值),返回的电话号码为空即使联系人“John Doe”存在于我的联系人列表中。

请帮忙!!!

试试这个

,而不是ContactsContract.CommonDataKinds.Phone.CONTENT_URIContactsContract.Contacts.CONTENT_URI参数查询方法。