Android Cursor Problem

▼魔方 西西 提交于 2020-01-15 07:46:31

问题


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;

    }

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.

Thanks,

~Elec0


回答1:


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.

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)




回答2:


cursor.close(); // in getRandomText()

after that you cannot obtain any data from the cursor - it is closed. Remove this line.



来源:https://stackoverflow.com/questions/5409864/android-cursor-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!