Search code examples
androidsharedpreferencesandroid-roomandroid-architecture-components

Accessing appcontext in repository for shared preferences (Architecture)


I am currently trying to wrap my head around the architecture components of the android platform, according to the official guide:

In my app I currently need to store a list of strings (names) and access it in multiple places (activities as well as services). 2 possible approaches come to my mind:

1) store them comma-separated in the shared preferences.
2) create an entity and room-table with the name as only column.

I would prefer the first approach since I only need the names as one single string to perform a contains()-operation. using a room database seems to be more of a hassle for this purpose.

My concrete Question is: is it okay to store the appcontext in the repository-class (which is a singleton) or am I breaking any conventions/architectural rules? Or would it be better to actually use room for this?


Solution

  • If you want to use the component architecture, and your repository needs to communicate with data sources that need a context, like room or SharedPreferences .. you'll need to extend your ViewModel from AndroidViewModel that will provide you a context that you can pass to your repository to use it to access the Room database or the SharedPreferences. there is no problem using a context in the repository, even if it is singleton, you already need it to access Room.