【问题标题】:Not able to retrieve data from contacts db无法从联系人数据库中检索数据
【发布时间】:2015-10-13 11:57:59
【问题描述】:

我正在使用以下代码:

preparePeople();
final Cursor c = mContext.getContentResolver().query(People.CONTENT_URI, mPROJECTION, null, null, null);
String s = c.getString(1);

private void preparePeople() {
    final ContentResolver mResolver = mContext.getContentResolver();
    mResolver.delete(People.CONTENT_URI, null, null);
    final ContentValues valuse = new ContentValues();
    valuse.put(People._ID, "1");
    valuse.put(People.NAME, "name");
    Uri uri = mResolver.insert(People.CONTENT_URI, valuse);
}

但在执行上述代码时,我得到如下异常:

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0

这是由于根据日志的 c.getString(1) 语句,但我不知道为什么.. 谁能帮忙解决这个错误?

【问题讨论】:

  • String s = c.getString(1);更改为String s = c.getString(0);
  • @MD,getString(0) 也有同样的问题,它打印: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

标签: android exception cursor indexoutofboundsexception cts


【解决方案1】:

首先,当您第一次获得Cursor 时,它位于第一行结果之前。致电moveToFirst()moveToPosition() 或其他方式将Cursor 移动到您想要的行。

其次,Cursor 中的列从 0 开始编号,计算机编程中的大多数情况也是如此。除非 mPROJECTION 有 2 个以上的条目,并且您真的想要索引为 1 的条目,否则您可能想要调用 getString(0),正如 MD 在评论中指出的那样。

第三,请记住there are cases where you might not get any results back,因此您可能需要在继续之前检查您从query() 返回的行数。

【讨论】:

  • 在调用 moveToFirst() 之后问题仍然存在,因为我尝试通过 getString(0) 获取值,我的 mPROJECTION 有 2 个条目,现在打印的日志是:android.database.CursorIndexOutOfBoundsException: Index 0请求,大小为 0
  • @KayPee:显然,您没有为查询返回任何行。
  • 是的@CommonsWare,我也提到了commonsware.com/blog/2015/10/12/…,但我的情况似乎没有权限问题。
  • @KayPee:那么您的insert() 似乎会失败。
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
  • 2018-07-09
  • 1970-01-01
相关资源
最近更新 更多