无法从ContactsContract收到电子邮件

时间:2015-04-20 20:28:18

标签: java android uri contactscontract

无论我尝试什么,它都行不通。 我之前尝试使用谷歌搜索和使用许多示例,我仍然继续得到indexOutOfBoundsException。

这是我的代码段。

Uri contactData = data.getData();



                String[] mProjection =
                        {

                                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                                ContactsContract.CommonDataKinds.Phone.NUMBER,
                                ContactsContract.CommonDataKinds.Email.DATA

                        };



                Cursor c =  getContentResolver().query(contactData,mProjection, null, null, null);

                myEmail = c.getString(c.getColumnIndexOrThrow(mProjection[2]));

                Log.d("EMAIL RESULT", myEmail);

有人能告诉我我做错了吗?

2 个答案:

答案 0 :(得分:0)

类似的问题:Android - Cursor not finding Column

你的代码似乎缺乏这个:

cursor.moveToFirst();

答案 1 :(得分:0)

这段代码对我有用:

    Cursor c;

    String[] projection = new String[]
            { ContactsContract.CommonDataKinds.Email._ID,
                    ContactsContract.CommonDataKinds.Email.DISPLAY_NAME_PRIMARY,
                    ContactsContract.CommonDataKinds.Email.ADDRESS
            };

    CursorLoader cursorLoader = new CursorLoader(
            this,
            ContactsContract.CommonDataKinds.Email.CONTENT_URI,
            projection,
            null,
            null,
            null);

    c = cursorLoader.loadInBackground();

    getEmails(c);

和你的getEmails方法:

 private void getEmails(Cursor c) {
        ContentResolver cr = getContentResolver();
        if (c.moveToFirst()) {
            do {
                String contactID = c.getString(c.getColumnIndex(
                        ContactsContract.CommonDataKinds.Email._ID));
                String contactDisplayName =
                        c.getString(c.getColumnIndex(
                                ContactsContract.CommonDataKinds.Email.DISPLAY_NAME_PRIMARY));
                String contactEmail =
                        c.getString(c.getColumnIndex(
                                ContactsContract.CommonDataKinds.Email.ADDRESS));


            } while (c.moveToNext());
        }
    }