19

Below is my codes and I got the android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2 error. Can anyone tell me how to solve it?

ContentResolver cr = getContentResolver();
  Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
    null, null, null, null);
  if (Integer.parseInt(cur.getString(
    cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {

   Cursor pCur = cr.query(
     Contacts.Phones.CONTENT_URI, 
     null, 
     Contacts.Phones.PERSON_ID +" = ?", 
     new String[]{id}, null);
   int i=0;
   int pCount = pCur.getCount();
   String[] phoneNum = new String[pCount];
   String[] phoneType = new String[pCount];
   while (pCur.moveToNext()) {
    phoneNum[i] = pCur.getString(
      pCur.getColumnIndex(Contacts.Phones.NUMBER));
    phoneType[i] = pCur.getString(
      pCur.getColumnIndex(Contacts.Phones.TYPE));
    i++;
   } 
  }
 }
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
user596379
  • 213
  • 1
  • 4
  • 11

1 Answers1

63

If you are accessing data from Cursor object than you must have to position the Cursor object.

Actually you have to position Cursor to the first row before you try to access data from it.

Put the line cur.moveToFirst(); after the line Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); in your code.

And also ensure that you are not using and older API for retrieving Contacts.

Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106
  • tks. i got another error nw. Caused by: java.lang.IllegalStateException: get field slot from row 0 col -1 failed – user596379 Jan 31 '11 at 06:47
  • 1
    It means probably you are using an Invalid column name. And if you only want to read contacts (mobile numbers) then have a look at this question http://stackoverflow.com/questions/1721279/how-to-read-contacts-on-android-2-0 – Vikas Patidar Jan 31 '11 at 07:41
  • ok. tks. i will try out the link. if i gt any further qns i will post it hre again. – user596379 Jan 31 '11 at 08:21
  • 1
    Yes, thanks, Vikas. I seem to forget to call moveToFirst() every few months (just long enough to forget how important it is!). – SMBiggs May 21 '12 at 06:06