【发布时间】:2015-08-25 10:30:44
【问题描述】:
背景
我有一个光标使用如下:
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 是将游标设置为 null cursor.close(); cursor = null; 大概是这样可以创建一个新游标,但没有区别,第二次循环它仍然给出 StaleDataException。
我已经试过了……
我尝试将其移出循环如下:
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();
但这不会编译并出现错误“光标可能尚未初始化”。
问题
我的问题是如何在循环中正确使用和关闭光标。
【问题讨论】:
-
虽然下面的答案解决了“光标在没有事先关闭的情况下完成”警告,但当片段被后台处理时,他们引入了一个新问题。请参阅以下问题:stackoverflow.com/q/32588271/1977132
标签: android android-cursor staledataexception