我想通过下面的代码获取电话号码,但是将号码设置为 EditText 字段似乎无效。
onActivityResult()
中的代码未向我提供所选联系人的联系人姓名。
EditText number;
public void chooseContact(View v) {
contact = (ImageView) findViewById(R.id.quickContact);
contact.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, PICK_CONTACT);
}
});
// Toast.makeText(getApplicationContext(), "hi contact is selected!!",
// Toast.LENGTH_SHORT).show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
ContentResolver cr = getContentResolver();
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null,
null, null);
if (c.moveToFirst()) {
id = c.getString(c
.getColumnIndex(ContactsContract.Contacts._ID));
name = c.getString(c
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(c.getString(c
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = ?", new String[] { id },
null);
while (pCur.moveToNext()) {
cnumber = pCur.getString(pCur
.getColumnIndex(Phone.NUMBER));
// Toast.makeText(getApplicationContext(), cnumber,
// Toast.LENGTH_SHORT).show();
number.setText(cnumber);
}
}
}
}
}
答案 0 :(得分:1)
尝试
number.setText(cnumber+"");
或
number.setText(String.valueOf(cnumber));
更新
改变你的逻辑
int i = 0;
while (pCur.moveToNext()) {
cnumber = pCur.getString(pCur
.getColumnIndex(Phone.NUMBER));
// Toast.makeText(getApplicationContext(), cnumber,
// Toast.LENGTH_SHORT).show();
if(i == 0){
number.setText(cnumber);
break;
}
}
这里。因为此循环只会在number
edittext中设置最后一个数字。
答案 1 :(得分:0)
您未在代码EditText
中找到number = findViewById(R.id.edittext)
,尝试查找并执行它。
答案 2 :(得分:-1)
它也显示错误。所以,要解决 -
id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
//Instead of this place String keyword at starting.
cnumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Place String keyword at starting.
name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Place String keyword at starting.