Android.database.CursorIndexOutOfBoundsException: requested index -1

I try to read all contacts using RawContacts.entityIterator, but I see this error:

android.database.CursorIndexOutOfBoundsException: requested index -1

Below is my code:

ContentResolver cr = getContentResolver(); Cursor cur = cr.query(Contacts.CONTENT_URI, null, null, 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, null, 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); } } 

Can someone please tell me what happened to my code.

+7
source share
2 answers

After running the query you should call cur.moveToFirst() ...

try it

 ContentResolver cr = getContentResolver(); Cursor cur = cr.query(Contacts.CONTENT_URI, null, null, null, null); if(cur != null && cur.moveToFirst()) { String id = cur.getString(cur.getColumnIndex(Contacts._ID)); if (cur.getCount() > 0) { ... 
+24
source

It is not necessary to call moveToFirst , but in order for you to moveToFirst to any of the returned lines before accessing the value (see moveToLast() , moveToPosition(int position) , ...).

So this is:

 Cursor cur = cr.query(Contacts.CONTENT_URI, null, null, null, null); while (cur.moveToNext()) { String id = cur.getString(cur.getColumnIndex(Contacts._ID)); final Uri uri = RawContactsEntity.CONTENT_URI; 

will work too - or even better, because there is a problem with the accepted answer , if you continue with ...

 while (cur.moveToNext()) { 

after

 if (cur.getCount() > 0) { 

It will skip the first line, which may not be obvious.

+2
source

All Articles