如何关闭在用于循环光标 [英] How to close a cursor used in a for loop

查看:201
本文介绍了如何关闭在用于循环光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我有一个游标使用方法如下:

I have a cursor used as follows:

        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()运行良好,但我得到一个警告游标,恕不另行接近敲定。

This gives a StaleDataException on the second time round the loop when it tries to reuse the closed cursor. If I remove cursor.close() it runs fine but I get a "Cursor finalized without prior close" warning.

研究

在这个答案的建议: http://stackoverflow.com/a/18107638/1977132 是设置光标到空 cursor.close();光标= NULL; presumably这样可以创建一个新的光标,但它并没有区别,第二次轮循环仍然给人一种StaleDataException

The advice in this answer: http://stackoverflow.com/a/18107638/1977132 is to set the cursor to null cursor.close(); cursor = null; presumably so a new cursor can be created, but it makes no difference, the second time round the loop it still gives a StaleDataException.

我已经尝试过...

我试过外循环移动,如下所示:

I tried moving it outside the loop as follows:

        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();

但不会与错误编译光标可能不被初始化。

but this wouldn't compile with the error "cursor might not have been initialized".

我的问题是我如何正确地使用一个循环内关闭游标。

My question is how do I correctly use and close a cursor within a loop.

推荐答案

试试这个

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();

这篇关于如何关闭在用于循环光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆