我有这个代码,有一个按钮让我从联系人中选择一个条目,并将该选择联系人传递给onActivityResult函数。我的问题是当所有传递的数据是数据变量中的Intent时,如何选择该单个联系人的数据。该数据变量,如果转换为字符串显示类似“dat:content:// contacts / people / 4”的内容,那么我看到选定的联系人以某种方式通过,但现在呢?如何获取数据?
我通过谷歌搜索发现的所有内容都是被弃用的类People的例子,所以我不知道如何使用新类。
public class HelloAndroid extends Activity {
private static final int CONTACT_ACTIVITY = 100;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button contactButton = (Button) findViewById(R.id.pick_contact_button);
contactButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("content://contacts/people");
Intent contacts_intent = new Intent(Intent.ACTION_PICK, uri);
startActivityForResult(contacts_intent, CONTACT_ACTIVITY);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case(CONTACT_ACTIVITY): {
if(resultCode == Activity.RESULT_OK) {
alertText(data.toString());
}
break;
}
}
}
}
答案 0 :(得分:1)
这将使光标保持基本联系人数据,并将循环通过联系人拥有的电话号码,可以有多个。
Uri uri = (Uri)data.toString();
Cursor cursor=ctx.getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know have the number so now query it like this
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
}