0

Ive done a lot of Googlig on this topic and I'm confused as to best practice.

Initially I had:

A) Created a DataBase object in my main class header area and then just passed it to functions as needed. I then later read that a DataBase should be opened and closed each time before use.

so then I:

B) went to each function (passing Context) which uses a SQL command and created a new DataBase object, created a filled cursor via SQL, and then closed the Database before returning. However, I then later read that it's expensive to do this.

now i'm thinking that:

C) I should create a new Database object in each subclass that uses one, and open and close it as needed.

Im sorry for the noob and seemingly design question (delete it if it's out of scope of StackOverflow), however, I truly am confused of how this should be handled to avoid errors, and how Google wants us to do it.

Regards

4

1 回答 1

1

Android 文档推荐使用SQLiteOpenHelper缓存数据库对象的. 从SQLiteOpenHelper参考:

一旦打开成功,数据库就会被缓存,所以每次需要写入数据库时​​都可以调用这个方法。(确保close()在不再需要数据库时调用。)

所以,我会选择一个带有 实例的单例SQLiteOpenHelper,这样你就可以从任何地方访问它。然后在需要的地方获取数据库,并在应用程序的退出点(如果有)将其关闭。这样,您只在需要时打开数据库,但也可以将相同的连接重新用于其他任务。

如果您确实只需要单个任务的数据库和/或有其他应用程序访问同一数据库,您可以考虑在数据库任务完成后直接关闭它;有一个关于关闭另一个问题的讨论。

于 2013-09-16T19:13:06.147 回答