从Android内置电话簿获取电子邮件ID和名称?

时间:2011-11-21 06:30:03

标签: android contacts android-contacts

我正在尝试将Android内置电话簿中的姓名和电子邮件ID添加到我的页面中,我可以获取姓名,联系人ID,电话号码。但是我无法从Android电话簿中获取电子邮件ID。

代码是:

 public static final int PICK_CONTACT = 1;
 @Override
 button.setOnClickListener(new OnClickListener() {
 public void onClick(View _view) {
 Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
 startActivityForResult(intent, PICK_CONTACT);  
   } 
 });
}

@Override 
public void onActivityResult(int reqCode, int resCode, Intent data) 
{
 super.onActivityResult(reqCode, resCode, data);

switch(reqCode) {
  case (PICK_CONTACT) : {
    if (resCode == Activity.RESULT_OK) {
      Uri contactData = data.getData();
      Cursor c = managedQuery(contactData, null, null, null, null);
      c.moveToFirst();
      String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
      String name1 = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
      String ContactID = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));

   if(Integer.parseInt(name1) == 1){
     Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,
     ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = " + ContactID, null, null);
     TextView tv = (TextView)findViewById(R.id.selected_contact_textview);
     TextView tv1 = (TextView)findViewById(R.id.selected_email_textview);
     tv.setText(name);
     tv1.setText(ContactID);
      }
      }
        break;
  }
 } 

在这里,我可以从电话簿中获取所选人员的姓名和联系人ID。现在我想从电话簿中获取所选人员的姓名和电子邮件ID。 我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用联系人ID直接获取联系人的电子邮件地址,如下所示:

    String selection = ContactsContract.CommonDataKinds.Email.CONTACT_ID + " =? ";
    String[] selectionArgs = new String[]{aContactId};
    Cursor emailCursor = aContext.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, selection, selectionArgs, null);
    while (!emailCursor.isAfterLast())
    {
        emailString = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// do something with email string
        emailCursor.moveToNext();
    }
    emailCursor.close ();