1

我正在尝试获取一个包含所有联系人姓名和生日的列表视图:

在我的 oncreate() 中:

final ListView listview = (ListView) findViewById(R.id.ListView1);
Cursor cursor=getContactsBirthdays();
SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,
    android.R.layout.two_line_list_item, cursor, 
    new String[] {ContactsContract.Contacts.DISPLAY_NAME, 
                  ContactsContract.CommonDataKinds.Event.START_DATE},
    new int[]{android.R.id.text1, android.R.id.text2});
listview.setAdapter(adapter);

我的 getContactsBirthdays() 方法:

private Cursor getContactsBirthdays() {
        try {
            Uri uri = ContactsContract.Data.CONTENT_URI;

            String[] projection = new String[] {
                    ContactsContract.Contacts.DISPLAY_NAME,
        //          ContactsContract.CommonDataKinds.Event.CONTACT_ID,
                    ContactsContract.CommonDataKinds.Event.START_DATE
            };

            String where = ContactsContract.Data.MIMETYPE + "= ? AND " +
                           ContactsContract.CommonDataKinds.Event.TYPE + "=" + 
                           ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
            String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
            return managedQuery(uri, projection, where, null, sortOrder);
        } catch (Exception e) {
            Log.e("Contact Error", "Error: " + e.getMessage());
            return null;
        }
    }

但我有一个非法参数异常:当我创建适配器时,列“_id”不存在。

有人可以解释我为什么吗?

4

2 回答 2

1

CursorAdapter 的文档SimpleCursorAdapter扩展):

游标必须包含名为“_id”的列,否则此类将不起作用。

于 2013-11-06T03:48:54.587 回答
0

我最终为此更改了代码:

private Cursor getContactsBirthdays() {
    try {
        Uri uri = ContactsContract.Data.CONTENT_URI;

        String[] projection = new String[] {
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID,
                ContactsContract.CommonDataKinds.Event.START_DATE
        };
        String where =
                ContactsContract.Data.MIMETYPE + "= ? AND " +
                ContactsContract.CommonDataKinds.Event.TYPE + "=" + 
                ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
        String[] selectionArgs = new String[] { 
            ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
        };
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
        return managedQuery(uri, projection, where, selectionArgs, sortOrder);
    } catch (Exception e) {
        Log.e("Contact Error", "Error: " + e.getMessage());
        return null;
    }
}
于 2013-11-06T04:09:51.887 回答