简体   繁体   English

Android数据库的多项活动

[英]Android database across several activities

I am currently trying to build an android application that has a tabbed view with 3 activities each in a tab. 我目前正在尝试构建一个具有选项卡式视图的android应用程序,每个选项卡中包含3个活动。 The activities each access a single database however android complains that second and third tabs don't have a lock on the database (because tab 1 would have gotten it because it was started first). 这些活动每个都访问一个数据库,但是android抱怨第二个和第三个选项卡没有对该数据库进行锁定(因为选项卡1会因为首先启动而获得了它)。 Does any one know what I should do to get this database accessible across the three tabs. 有谁知道我应该怎么做才能通过三个选项卡访问此数据库。

Try taking a look at this Sharing sqlite database between multiple Android Activities using on resume and on pause looks like it could solve your issue. 尝试查看一下多个Android活动之间的共享SQLite数据库,使用恢复和暂停看起来可以解决您的问题。

Hope this helps. 希望这可以帮助。

Open the database once on app startup (create an Application subclass if you don't already have one), and don't ever close the database. 应用程序启动时(创建一个开放的数据库中,一旦 Application子类,如果你不已经有一个),并且永远不要关闭数据库。 Share the database between your activities using a Singleton or an accessor method in your Application class. 使用Singleton或Application类中的访问器方法在活动之间共享数据库。

SQLite itself manages sequential access between competing threads if needed, so you don't need to manage locking yourself. SQLite本身可以根据需要管理竞争线程之间的顺序访问,因此您不需要管理自己的锁定。 You don't need to close the database since SQLite's transactional nature means it flushes everything to storage at the earliest opportunity anyway. 您无需关闭数据库,因为SQLite的事务性质意味着无论如何它都会尽早将所有内容刷新到存储中。

Your code becomes much simpler and safer if you do it this way. 如果这样做,您的代码将变得更加简单和安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM