2011-03-23 71 views
2

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

 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; 

    } 

这里是我的代码,它返回后读取光标。

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

我可能犯了一个愚蠢的错误,没有意识到它,但我无法弄清楚这一点。

感谢,

〜Elec0

+0

你不能在你要返回的光标上调用close(),然后使用它。删除该行,并在完成后关闭一次。 – LeffelMania 2011-03-23 18:32:15

回答

3

您在返回之前关闭()您的光标。从它返回的位置开始,然后尝试调用moveToFirst()。如果光标关闭,则无法完成此操作。

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

+0

这是真的。那么我会那样做。谢谢。 – Elec0 2011-03-23 18:56:23

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

之后,你不能获得光标任何数据 - 它是封闭的。删除这一行。