简体   繁体   中英

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. 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). 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.

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. Share the database between your activities using a Singleton or an accessor method in your Application class.

SQLite itself manages sequential access between competing threads if needed, so you don't need to manage locking yourself. You don't need to close the database since SQLite's transactional nature means it flushes everything to storage at the earliest opportunity anyway.

Your code becomes much simpler and safer if you do it this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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