我想从联系人中检索手机号码(我想发送短信)。这是我的代码:
//Selecting the contact
Button buttonPickContact = (Button)findViewById(R.id.pickcontact);
buttonPickContact.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, RQS_PICK_CONTACT);
}});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Cursor cursor = null;
mName.setText(context.getString(R.string.not_available));
mNumber.setText(context.getString(R.string.not_available));
if(requestCode == RQS_PICK_CONTACT && resultCode == RESULT_OK && data != null){
Log.d(TAG, "requestCode, resultCode, data ok");
Uri uri = data.getData();
try{
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER};
// cursor = getContentResolver().query(uri, projection, null, null, null);
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
Log.d(TAG, "Trying to retrieve the name and the number");
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String hasNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER));
Log.d(TAG, "hasNumber "+hasNumber);
mName.setText(name);
if(hasNumber.trim().equals("1")){
Log.d(TAG, "contact has telephone number");
//set name and number
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
mNumber.setText(phoneNumber);
}
}catch(Exception ex){
CharSequence text = context.getString(R.string.cannot_choose_contact);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if(cursor!= null && !cursor.isClosed()){
cursor.close();
}
}else{
CharSequence text = context.getString(R.string.cannot_choose_contact);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
我收到:无法从CursorWindow读取第0行,第-1列......
如何获取电话号码 - 我是否尝试从右栏中检索电话号码?
提前感谢您的回答,
答案 0 :(得分:1)
联系人的详细数据包含在与主要联系人本身不同的表格中(有关详细信息,请参阅Contacts API guide)。由于您正在发送短信,因此仅获取与电话号码相关联的联系人可能更有用,因此您也可以直接查找包含电话号码的表格。对于URI,我使用:
CommonDataKinds.Phone.CONTENT_URI
然后您不必担心HAS_PHONE_NUMBER
。一目了然,其余代码看起来正确或非常接近。如果您想继续沿原始路径前进,则无论如何都必须对此表进行单独查询,但要为其提供您最初找到的联系人的ID。
答案 1 :(得分:1)
mLookupKey = uri.getLastPathSegment(); 字符串SELECTION = Data.LOOKUP_KEY +“=?”+ “和”+ Data.MIMETYPE +“=?”; String [] selectionArgs = { mLookupKey, Email.CONTENT_ITEM_TYPE }; ...