Android java.lang.IllegalArgumentException:检索联系人时出现列_count错误

时间:2011-12-14 17:05:11

标签: android android-contacts illegalargumentexception

我正在开展一个项目,我需要列出所有联系人。我正在关注this article

我的 AndroidManifest.xml 包含在下面,所以我可以阅读联系人:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

代码在这里

private void getContacts() {
    try {
        // Form an array specifying which columns to return. 
        String[] projection = new String[] {
                                    People._ID,
                                    People._COUNT,
                                    People.NAME,
                                    People.NUMBER};

        // Get the base URI for the People table in the Contacts content provider.
        Uri contacts =  People.CONTENT_URI;

        // Make the query. 
        Cursor managedCursor = managedQuery(contacts,
                                    projection, // Which columns to return 
                                    null,       // Which rows to return (all rows)
                                    null,       // Selection arguments (none)
                                    // Put the results in ascending order by name
                                    People.NAME + " ASC");

        printContacts(managedCursor);
    }
    catch(Exception ex) {
        Log.d("Contacts",ex.toString());
    }
}

private void printContacts(Cursor cur){ 
    if (cur.moveToFirst()) {
        String name; 
        String phoneNumber; 
        int nameColumn = cur.getColumnIndex(People.NAME); 
        int phoneColumn = cur.getColumnIndex(People.NUMBER);
        String imagePath; 

        do {
            // Get the field values
            name = cur.getString(nameColumn);
            phoneNumber = cur.getString(phoneColumn);
            Log.d("Contacts","Name: "+ name + " **** Phone: "+ phoneNumber);
        } while (cur.moveToNext());
    }
}

当我在模拟器(2.3.3)上运行时,它会抛出以下错误:

java.lang.IllegalArgumentException: Invalid column _count

有人能解决吗? 非常感谢您宝贵的时间和帮助

2 个答案:

答案 0 :(得分:2)

如果删除字符串People._COUNT,一切正常

另请参阅:Android SDK - List All Users

答案 1 :(得分:1)

不推荐使用Android People类。您应该使用ContactsContract代替。 由于您在Emulator API级别10上运行它,并且自API级别5以来不推荐使用该类,因此没有理由继续使用People。