背景
我有一个游标使用如下:
for (int n=0; n<num_songs; n++) {
boolean isChecked = checked_positions.get(n);
if (isChecked) {
Cursor cursor = (Cursor) getListView().getItemAtPosition(n);
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
cursor.close();
//save artist and title strings to file...
}
}
当它尝试重用关闭的游标时,这会在第二次循环中产生 StaleDataException。如果我删除 cursor.close() 它运行良好,但我得到一个“光标在没有事先关闭的情况下完成”警告。
研究
此答案中的建议:https ://stackoverflow.com/a/18107638/1977132 大概将光标设置为 nullcursor.close(); cursor = null;
以便可以创建一个新光标,但这没有区别,第二次循环它仍然给出一个过时的数据异常。
我已经试过了...
我尝试将它移到循环之外,如下所示:
Cursor cursor;
for (int n=0; n<num_songs; n++) {
boolean isChecked = checked_positions.get(n);
if (isChecked) {
cursor = (Cursor) getListView().getItemAtPosition(n);
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
//save artist and title strings to file...
}
}
cursor.close();
但这不会编译错误“光标可能尚未初始化”。
问题
我的问题是如何在循环中正确使用和关闭游标。