Android: 使用phone号码获取联系人姓名

Android: Get contact name using phone number

我正在尝试访问联系人,但一直出现空指针错误。

NullPointerException: Attempt to invoke virtual method ' android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference

代码

 public static String getContactName(Context context, String phoneNumber) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cursor = context.getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
    if (cursor == null) {
        return null;
    }
    String contactName = null;
    String contactNumber = "";
    if(cursor.moveToFirst()) {
        contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
    }

    if(cursor != null && !cursor.isClosed()) {
        cursor.close();
    }

    return contactNumber.equals("") ? phoneNumber : contactName;
}

下面是我的使用方法

public class VideoActivity extends Activity {

String contactName;
String phoneNumber;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_video);

    //Set caller phone
    String number = getIntent().getStringExtra(
            TelephonyManager.EXTRA_INCOMING_NUMBER);

   contactName = getContactName(context, number);
    TextView text = (TextView) findViewById(R.id.textView2);
    text.setText(contactName);

}

是否可以在 activity 中调用 BroadcastReceiver?

如有任何帮助,我们将不胜感激。谢谢

private void ContactList(){
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER;
        Cursor cursor = context.getContentResolver().query(uri, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}, selection, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");


        cursor.moveToFirst();
        while (cursor.isAfterLast() == false) {

            String contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            }
            cursor.moveToNext();
        }
        cursor.close();
        cursor = null;

      }

你没有在 activity 中初始化值 context,你是从 activity 调用的,所以你可以这样调用,

contactName = getContactName(this, number);

或者您可以设置上下文值并像这样调用,

context = this;
contactName = getContactName(context, number);