我在网上看到大量帖子显示“如何打开Android联系人列表”,但它们都已过时,部分代码甚至不再有效。
编辑:
现在有以下内容:
public class MessagePreview extends Activity {
final int PICK_CONTACT = 3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button recipientContact = (Button) findViewById(R.id.buttonAddRecipient);
recipientContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
}
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndexOrThrow(People.NAME));
// TODO Whatever you want to do with the selected contact
// name.
}
}
break;
}
}
}
没有错误,但它确实说
在这一行:
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
我必须在该行之后添加更多代码,但我不知道要添加什么。
答案 0 :(得分:0)
您正在尝试在另一个方法中定义方法。这不起作用。请将onActivityResult()
的定义移至Activity
上。
FWIW,here is a sample application选择适用于Android 1.5-4.0.3的联系人。
答案 1 :(得分:0)
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(contactData , projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
String number = names.getString(indexNumber);
} while (names.moveToNext());
在onactivityforresults上尝试此代码