android.database.CursorIndexOutOfBoundsException:索引-1请求

我正在尝试使用RawContacts.entityIterator读取所有联系人,但我看到了这个错误

android.database.Cursorindexoutofboundsexception:索引-1请求

以下是我的代码

ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(Contacts.CONTENT_URI,null,null);

String id = cur.getString(cur.getColumnIndex(Contacts._ID));

if (cur.getCount() > 0) {
        while (cur.movetoNext()) {
         final Uri uri = RawContactsEntity.CONTENT_URI;
            final String selection = Data.CONTACT_ID + "=?";
            final String[] selectionArgs = new String[] {id};

            final Map<String,List<ContentValues>> contentValuesListMap =
                new HashMap<String,List<ContentValues>>();
            EntityIterator entityIterator = null;

            entityIterator = RawContacts.newEntityIterator(cr.query(
                    uri,selection,selectionArgs,null));

            while (entityIterator.hasNext()) {
                Entity entity = entityIterator.next();
                for (NamedContentValues namedContentValues : entity.getSubValues()) {
                    ContentValues contentValues = namedContentValues.values;
                    String key = contentValues.getAsstring(Data.MIMETYPE);
                    if (key != null) {
                        List<ContentValues> contentValuesList =
                                contentValuesListMap.get(key);
                        if (contentValuesList == null) {
                            contentValuesList = new ArrayList<ContentValues>();
                            contentValuesListMap.put(key,contentValuesList);
                        }
                        contentValuesList.add(contentValues);
                    }
                }
            }
            Log.i(tag,"Contact index=" + id);
        } 
    }

有人可以告诉我我的代码有什么问题.

解决方法

执行查询后,必须调用cur.movetoFirst()…

试试这个

ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(Contacts.CONTENT_URI,null);

if(cur != null && cur.movetoFirst())
{
       String id = cur.getString(cur.getColumnIndex(Contacts._ID));

        if (cur.getCount() > 0) {
         ...

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...