如何关闭 for 循环中使用的游标

How to close a cursor used in a for loop

背景

我有一个光标使用如下:

        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() 它运行正常但我收到 "Cursor finalized without prior close" 警告。

研究

这个答案中的建议: 是将游标设置为 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();

但这不会编译并出现错误 "cursor might not have been initialized"。

问题

我的问题是如何在循环中正确使用和关闭游标。

试试这个

Cursor cursor = null;
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...
    }
}
if(cursor != null)
    cursor.close();

这是关闭游标的正确方法:

    Cursor cursor = null;
    try{
        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...
            }
        }
    } finally {
        if(cursor != null){
            cursor.close();
        }
    }