19

下面是我的代码,我得到了android.database.CursorIndexOutOfBoundsException:请求索引 -1,大小为 2 错误。谁能告诉我如何解决它?

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++;
   } 
  }
 }
}
4

1 回答 1

62

如果您从Cursor对象访问数据,则必须定位Cursor对象。

实际上,Cursor在尝试从中访问数据之前,您必须定位到第一行。

将行放在代码中的行cur.moveToFirst();之后Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

并确保您没有使用旧 API 来检索联系人。

于 2011-01-31T06:30:46.230 回答