[英]why am i getting Null Pointer Exception?
我正在使用此代码从数据库中获取数据:
Cursor cursor = db.query(News_Table, null, null, null, null, null, null);
if (cursor != null)
{
cursor.moveToFirst();
}
allNews = new News[cursor.getCount()];
int i = 0;
while (!(cursor.isLast()))
{
allNews[i] = new News(cursor.getInt(0), cursor.getString(2),
cursor.getString(1));
cursor.moveToNext();
i++;
}
这是我的桌子的样子:
但是每次我的最后一行都没有被获取时,我会得到一个空指针异常。 这是日志猫屏幕:
为什么我的代码只能正确运行n-1行,并在第(n)行出现问题,其中n是新闻表中的总行数。
当光标位于最后一行时,cursor.isLast()将返回true,因此,您的while循环将在未读取并处理最后一行的那一点处停止。 通常,用于迭代游标的模式将是(请注意,这也不会调用moveToFirst()
)
Cursor cursor = getACursor();
int i = 0;
while (cursor.moveToNext()) {
/// do something with this row
allNews[i] = new News(cursor.getInt(0), cursor.getString(2),cursor.getString(1));
i++;
}
while (!(cursor.isLast()))
我认为问题不是isLast()
。 您是在明确地说是否不是最后一行。
将while循环更改为:
while (cursor.moveToNext()) {
//Your code.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.