我正在尝试访问联系人,但一直收到空指针错误。Android:使用电话号码获取联系人姓名
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);
}
是否可以调用广播接收器中的活动?
任何帮助将不胜感激。由于
你怎么称呼你的getContactName。你的上下文看起来是空的,因此也是错误。你可以在你的文章 –
中添加方法调用代码,你的上下文为空,你可以从你调用的方法显示方法 –
好的。我会添加它 – Olalekan