Android: Accessing single database from multiple activities in application?

前端 未结 4 1033
星月不相逢
星月不相逢 2020-12-16 17:29

I have a todo list type application that stores all of the note data in a sqlite3 database. Each activity in the application needs access to the database to edit different

相关标签:
4条回答
  • 2020-12-16 17:36

    In my opinion, the Content Provider is complicated and if you are not sharing with activities that are not your own, you don't need it. Therefore, I suggest you use a singleton class first. Then if you have more time or need it, go for the Content Provider.

    I've used a singleton successfully for 6 months without much difficulty. (I was careful to really make it a singleton though, only one instance that loads the data once)

    Singleton

    • Advantage: Easy to implement
    • Advantage: because I used a common instance, I could implement caching easily and hence make the application not have to do to the database as often
    • Disadvantage:can't share your data with external Activities

    Content Provider

    • Advantage: You can share your data with external Activities
    • Advantage: You can integrate with the Search API
    • Disadvantage: Complicated, need to represent your data in a different way
    • Disadvantage: Yet another Android API to spend time learning
    0 讨论(0)
  • 2020-12-16 17:54

    It is 2018 and in the meantime Android has evolved.

    The Android architecture component that is recommended for this use case today is Android Room.

    0 讨论(0)
  • 2020-12-16 17:57

    The recommended way to do this on Android is to use a ContentProvider. Your first content provider may feel like more trouble than it's worth, but once you get the pattern down it shouldn't be too bad provided you aren't trying to serialize blobs.

    0 讨论(0)
  • 2020-12-16 18:01

    This is causing problems though

    Which are...what?

    and I would like a slightly more global access solution so I don't have to keep opening/closing/creating a database.

    Opening and closing a SQLite database is cheap. Statics and singletons are to be avoided wherever possible. What makes you think your current solution is bad?

    0 讨论(0)
提交回复
热议问题