synchronized methods in Android Activities

旧城冷巷雨未停 提交于 2019-12-11 02:59:24

问题


I have two activities. In activity 1 I write a value to a SQLite database by entering that value into an EditText field. Once I press the submit button, the data is written and I am moved along to another activity - activity 2. Activity2 also does the same thing in that I can write new data and persist it to the database with a button click. So, my question is: do I need to synchronize the method (which is on a separate thread from the UI) in activity 1, as well as the method in activity 2 in order to prevent thread safety issues in the database? Keep in mind that both methods access the same database but from different activities. Technically, activity 1 should be complete with onStop having been called and the new activity (activity 2), now being visible. Is it even possible for these two activities and their corresponding threads accessing the database (via different methods) to have any kind of concurrency problems given the Android activity life cycle?

Thanks very much, Matt


回答1:


Check this method

SQLiteDatabase.setLockingEnabled(boolean lockingEnabled)



回答2:


How is your background thread created? A background thread will continue to run even after an activity has been stopped.

If data in activity 2 will not be persisted until the user has entered some data, then it seems like a lock would be unnecessary given the fact that the data from activity 1 should persist in a matter of milliseconds.

However, if you're preparing for the worst case scenario, I don't see how a database lock would hurt anything (as @Pepi suggested). The only way I can see this being a problem is if work being done in your background thread (activity 1) is hanging on something before it can commit the data. If activity 2 starts it's own background worker to commit data, then you could potentially have a race between these two background threads.



来源:https://stackoverflow.com/questions/6306522/synchronized-methods-in-android-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!