我想从本地联系人那里获取电话号码,但是有问题。例如,如果我选择人 A,那么显示的号码是人 B 的。这是代码。
//the button_click
public void testM(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
MainActivity.this.startActivityForResult(intent, 1);
}
//
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
final EditText phoneText = (EditText) findViewById(R.id.editText1);
switch (requestCode) {
case (1): {
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
c.moveToFirst();
String phoneNum = this.getContactPhone(c);
phoneText.setText(phoneNum);
}
break;
}
}
}
// get the number
private String getContactPhone(Cursor cursor) {
int phoneColumn = cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER);
int phoneNum = cursor.getInt(phoneColumn);
String phoneResult = "";
// System.out.print(phoneNum);
if (phoneNum > 0) {
// get the id
int idColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
String contactId = cursor.getString(idColumn);
// get cursor;
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
+ contactId, null, null);
// int phoneCount = phones.getCount();
// allPhoneNum = new ArrayList<String>(phoneCount);
if (phones.moveToFirst()) {
// traverse all the phone number
for (; !phones.isAfterLast(); phones.moveToNext()) {
int index = phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int typeindex = phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int phone_type = phones.getInt(typeindex);
String phoneNumber = phones.getString(index);
switch (phone_type) {
case 2:
phoneResult = phoneNumber;
break;
}
// allPhoneNum.add(phoneNumber);
}
if (!phones.isClosed()) {
phones.close();
}
}
}
return phoneResult;
}
我知道'ContactsContract.CommonDataKinds'一定有问题。我不熟悉这个类。