Android游标问题 [英] Android Cursor Problem

查看:172
本文介绍了Android游标问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图从SQLite数据库的值到游标,然后选择一个随机值。我可以用getString()读取游标,就像我通常在方法中一样,但是在它返回游标后,它不能正常工作。我不知道为什么..
这里是我从数据库获取光标的方法。

So I'm trying to get the values from a SQLite database into a cursor, then pick a random value. I can read the cursor with getString() as I normally would in the method, but after it returns the cursor it doesn't work correctly. I don't know why.. Here's my method for getting the cursor from the database. It seems to work correctly.

        public Cursor getRandomText(String Rating)
    {

        Cursor cursor = myDatabase.query("Elec0RandTexts", new String[] {"Message"}, "Rating=?", 
                new String[]{Rating}, null, null, null);
        cursor.moveToFirst();

        cursor.close();

        return cursor;

    }

这是我的代码,用于读取游标返回后。 / p>

Here's my code for reading the cursor after it's returned.

            Cursor result = dbh.getRandomText(Rating);
        result.moveToFirst();

        int RandText = rand.nextInt(result.getCount());

        result.moveToPosition(RandText);
        Toast.makeText(getApplicationContext(), "" + result.getString(RandText), Toast.LENGTH_LONG).show();

        result.close();

我可能犯了一个愚蠢的错误,没有意识到,但我不明白

I'm probably making a stupid mistake and not realizing it, but I can't figure this out.

感谢,

〜Elec0

推荐答案

您在返回之前关闭()您的Cursor。从返回的位置,然后尝试调用moveToFirst()。

You close() your Cursor before you return it. From where it is returned to, you are then attempting to call moveToFirst(). This cannot be done if the Cursor is closed.

在getRandomText(String)方法中,您应该从Cursor返回有意义的数据,而不是Cursor对象本身。这样,创建Cursor的方法可以继续关闭Cursor,因为它应该。 (它应该只发生在方法的结尾)

In your getRandomText(String) method, you should return the meaningful data from your Cursor, rather than the Cursor object itself. That way, the method that created the Cursor can continue to close the Cursor as it should. (It should just happen at the end of the method)

这篇关于Android游标问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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