我正在做一个简单的应用程序,我有一个 edittext 字段和一个按钮,该按钮有一个 onclick 事件。代码如下所示:
private static final int CONTACT_PICKER_RESULT = 1;
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
我正在调用联系人选择器活动,当我选择一个联系人时,我想在编辑文本字段中填充联系人的姓名。
代码如下所示:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
String contactname = "";
// use the contact provider to get the contact details
Uri result = data.getData();
Cursor cursor = getContentResolver().query(result, null, null, null, null);
int idx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
contactname = cursor.getString(idx);
EditText name = (EditText) findViewById(R.id.editText1);
name.setText(contactname);
cursor.close();
}
所有这些代码都包含在onCreate()
主要活动中。
当我在模拟器中运行应用程序并单击按钮时,我正在获取联系人列表(我在模拟器中创建了 3 个联系人)。当我选择一个联系人时,我在 DDMS 中遇到错误。错误是:
06-09 19:24:16.188: ERROR/AndroidRuntime(7158): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1