【发布时间】:2018-08-30 21:24:00
【问题描述】:
代码如下:
button.setOnClickListener(new View.OnClickListener() {
@Override public void onClick (View view){
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}); return view;}
public void but(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
Uri uri = data.getData();
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
if (phoneNo.startsWith("+")) {
if (phoneNo.length() == 13) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
if (phoneNo.length() == 16) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
} else {
editText.setText(phoneNo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
【问题讨论】:
-
Masresha 您的代码中的任何引用都可能为空,或者只是您的光标为空,或者您没有足够的权限来使用您打算使用的服务。但关键是,如果您查看 Logcat 输出,则很难从代码中分辨出来。在 Android Studio 中找到底部的选项卡,并在那里查找您的致命错误。祝你好运!
-
嗨,Masresha,如果可能的话,能否请您发布您的整个课程和日志?
-
您需要检查崩溃的堆栈跟踪,它会引导您找到崩溃的确切行,请参阅:stackoverflow.com/questions/3988788/…
标签: android fragment onclicklistener android-contacts buttonclick