可能会是一个非常简单的解决方案的完整的n00b问题,但我的应用程序上有一个SQLite数据库,我通过内容提供商访问它。
在其中一个活动中,我试图查询一个表(picturesTable),该表包含图像的路径和一个(itemTable)的外键。
我希望查询过滤itemTable _id字段(保存在pictureTable中的外键)返回的图片。
在测试时,我只是在TextView中显示返回的路径。字符串ItemId将作为intentExtra从上一个活动中传递。
Uri imgUri = mProvider.CONTENT_URI;
String[] columns = mDbHelper.ALL_IMG_COLUMNS;
String selection = mDbHelper.IMG_ITEM_ID;
String[] selectionArgs = new String[]{ItemId};
String groupBy = null;
Cursor imgCursor = getContentResolver().query(imgUri, columns,
selection , selectionArgs, groupBy);
String imgPath = "";
assert imgCursor != null;
imgCursor.moveToFirst();
do {
imgPath += imgCursor.getString(
imgCursor.getColumnIndex(mDbHelper.IMG_PATH)) + "\n";
imgPath += "Image ID " + imgCursor.getString(
imgCursor.getColumnIndex(mDbHelper.IMG_TREE_ID)) + "\n" + "\n";
} while (imgCursor.moveToNext());
imgCursor.close();
tv.setText(imgPath);我遇到的问题是,目前,它只是返回picturesTable中的最后一项。
如果我将selection更改为mDbHelper.IMG_ITEM_ID + " = ?",应用程序在运行时会崩溃。
如果我像预期的那样将selection和selectionArgs更改为null,我将获得所有返回的项。
任何关于我能做什么来解决这个问题的建议都会得到极大的接受,因为现在我要疯了!
发布于 2017-11-13 03:50:02
您的问题可能是由于没有数据与WHERE子句匹配而返回的空游标。
空游标与查询永远不会返回的null游标截然不同。因此,assert对空的或已填充的游标没有影响(假设这是断言的目的)。
如果没有要移动到的第一行,游标的moveToFirst方法将返回false,就像空游标的情况一样。但是,由于未选中此项,因此对待/处理空游标的方式与填充的游标没有区别。
使用do... while时,如果存在空游标,而不是填充的游标,则imgPath += imgCursor.getString( imgCursor.getColumnIndex(mDbHelper.IMG_PATH)) + "\n";将导致异常,因为没有可从中检索数据的有效行。
由于像moveToFirst一样的moveToNext将返回false,如果不能进行移动,那么我建议最简单的解决方案是不处理数据,至少对于这部分代码来说是这样:-
assert imgCursor != null;
imgCursor.moveToFirst();
do {
imgPath += imgCursor.getString(
imgCursor.getColumnIndex(mDbHelper.IMG_PATH)) + "\n";
imgPath += "Image ID " + imgCursor.getString(
imgCursor.getColumnIndex(mDbHelper.IMG_TREE_ID)) + "\n" + "\n";
} while (imgCursor.moveToNext());与:-
while (imgCursor.moveToNext) {
imgPath += imgCursor.getString(
imgCursor.getColumnIndex(mDbHelper.IMG_PATH)) + "\n";
imgPath += "Image ID " + imgCursor.getString(
imgCursor.getColumnIndex(mDbHelper.IMG_TREE_ID)) + "\n" + "\n";
}这样就不会尝试为空游标向imgPath赋值。
当然,这不会解决返回空游标的潜在问题。
https://stackoverflow.com/questions/47250865
复制相似问题