且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的SQLite的SQLiteOpenHelper IllegalStateException异常 - 数据库已经关闭错误

更新时间:2023-01-12 20:01:20

既然这个问题已经得到了大量的关注,我想回答这个问题,并说明我学到的东西,并为我工作来纠正这个问题,我的大,数据库驱动的应用程序:

Since this question has gotten a good deal of attention, I wanted to answer it and describe what I've learned and what worked for me to correct this problem in my large, database-driven application:

  1. 不要使用管理游标。还有一个原因,为什么他们去precated。他们是完全有问题。实际上,有极少数的情况下,您确实需要使用托管光标反正。相反,运行查询,并填充对象的结果。如果要查询的多行,创建一个ArrayList<您的对象>来保存所有行。我现在要做的就是创建一个运行查询,并通过我回到我的ArrayList℃的功能;>而不是光标的回报。我关闭游标函数内,我就完了。对于一个列表视图,您将不再能够使用SimpleCursorAdapter。只要把所有这些为BaseAdapter和使用您的ArrayList<>对象来填充它

  1. Do NOT use managed cursors. There's a reason why they're deprecated. They're completely problematic. Realistically, there's very few scenarios where you actually need to use a managed cursor anyway. Instead, run your query and populate an object with the results. If you're querying for multiple row, create an ArrayList<> of your object to hold all the rows. What I do now is create a function that runs the query and passes me back my ArrayList<> rather than a cursor in the return. I close the cursor within the function and I'm done. For a ListViews, you'll no longer be able to use a SimpleCursorAdapter. Just convert all of these to a BaseAdapter and use your ArrayList<> object to populate it.

不要忘记关闭所有游标。这也可以严重破坏你的应用程序的数据库连接。我想我这样做,但,果然,发现我并没有显式关闭光标的位置。因此,通过你的应用程序,并仔细检查所有的人。

DO NOT FORGET TO CLOSE ALL YOUR CURSORS. This can also wreak havoc on your app's db connections. I thought I was doing this but, sure enough, found a spot that I wasn't explicitly closing a cursor. So, go through your app and double check all of them.

我还使用一个单独DatabaseHelper对象。我在我的SQLiteOpenHelper类中声明静态DatabaseHelper对象,这样我每次都得到相同的实例。

I'm also using a singleton DatabaseHelper object. I declare a static DatabaseHelper object within my SQLiteOpenHelper class so that I'm getting the same instance every time.

我现在有一个稳定运行的应用程序,不再得到这些DB错误。我希望这些信息是有帮助的一些你。

I now have a stable running app that no longer gets these DB errors. I hope this information is helpful to some of you.