无法获取电子邮件地址

时间:2013-08-06 14:31:43

标签: android android-contacts

这个问题已经被问到Getting contact email by name但是这对我没用。我有以下代码来获取电子邮件地址,但遗憾的是它无效。任何人都有助于解决这个问题。

ContentResolver cr = getContentResolver();
Cursor emailCur = cr.query( 
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
                null,
                ContactsContract.CommonDataKinds.Email.Display_Name + " = ?", 
                new String[]{name}, null); 
TextView tv2 = (TextView) findViewById(R.id.textView5);

while (emailCur.moveToNext()) { 
                String email = emailCur.getString(
                              emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                String emailType = emailCur.getString(
                              emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); 
                tv2.setText(email);
                Toast.makeText(getApplicationContext(), ""+email, Toast.LENGTH_LONG).show();
            } 
            emailCur.close();

我也尝试使用contact_id。

1 个答案:

答案 0 :(得分:0)

这可能对您有所帮助

public static void getContactEmails(Context context) {
        String emailIdOfContact = null;
        int emailType = Email.TYPE_WORK;
        String contactName = null;


            ContentResolver cr = context.getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                    null, null, null);
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur
                            .getColumnIndex(BaseColumns._ID));
                    contactName = cur
                            .getString(cur
                                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    // Log.i(TAG,"....contact name....." +
                    // contactName);

                    cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                    + " = ?", new String[] { id }, null);

                    Cursor emails = cr.query(Email.CONTENT_URI, null,
                            Email.CONTACT_ID + " = " + id, null, null);
                    while (emails.moveToNext()) {
                        emailIdOfContact = emails.getString(emails
                                .getColumnIndex(Email.DATA));
                        // Log.i(TAG,"...COntact Name ...."
                        // + contactName + "...contact Number..."
                        // + emailIdOfContact);
                        emailType = emails.getInt(emails
                                .getColumnIndex(Phone.TYPE));


                    }
                    emails.close();

                }
            }// end of contact name cursor
            cur.close();


    }