【发布时间】:2012-01-26 00:53:33
【问题描述】:
在我的应用程序中,我有一个 AutoComplete TextView 和 EditText 在这个 AutoComplete TextView 提供了来自联系人的所有联系人姓名。
我想获取在我的自动完成文本视图中选择的联系人的主要电子邮件 ID 到 editText。我怎样才能做到这一点?有人指导我吗?
【问题讨论】:
标签: android email android-contacts
在我的应用程序中,我有一个 AutoComplete TextView 和 EditText 在这个 AutoComplete TextView 提供了来自联系人的所有联系人姓名。
我想获取在我的自动完成文本视图中选择的联系人的主要电子邮件 ID 到 editText。我怎样才能做到这一点?有人指导我吗?
【问题讨论】:
标签: android email android-contacts
public class Contact extends Activity {
/** Called when the activity is first created. */
private static final int CONTACT_PICKER_RESULT = 10;
private static final String DEBUG_TAG = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.invite_email);
emailEntry.setText(email);
if (email.length() == 0) {
Toast.makeText(this, "No email found for contact.",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
}
【讨论】:
确保您的应用拥有READ_CONTACTS 权限。
AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null, null, null);
startManagingCursor(emailCursor);
autoCompleteTextView.setAdapter(new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, emailCursor, new String[] {Email.DATA1}, new int[] {android.R.id.text1}));
autoCompleteTextView.setThreshold(0);
请注意 AutoCompleteTextView 区分大小写。
【讨论】: