我想获取本地联系人的电话号码,但是有问题。例如,如果我选择 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'肯定有问题。我不熟悉这个类。
最佳答案
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
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 = getContentResolver().query(contactData, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, null);
if (c.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
String phoneNum = c.getString(columnIndex);
phoneText.setText(phoneNum);
}
}
break;
}
}
关于java - 电话号码不对,使用 "ContactsContract",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16870470/