I want to use SharedPreferences between multiple activities and the idea is that I'll have one class that access the SharedPreferences and returns it to different activities via static methods. My question is: since SharedPreferences needs a context to be initialized and I'll be giving it different contexts from different activities will the values still be accessible?
All help is appreciated!
In Android, we can create a new SharedPreference file or access an existing one by calling one of these methods: >getSharedPreferences() - This method is used if you need multiple SharedPreference files identified by name, which you specify with the first parameter. This method calls from any context in your app.
SharedPreferences are not intended to store a lot of data, there is no limit per se (since it is an xml file), but for larger sets of data, I would suggest using Room (or SQLite for the older projects). There is also another reason why storing in a database makes more sense.
It stores structured data as a database. The data can be queried and hence ,this makes it possible to search database. Reading data from sqlite database is slower and more expensive then shared preferences. SQLite database is useful for just about anything and very flexible.
There are 2 templates and samples: SharedPreferences Singleton that uses String keys. SharedPreferences Single that uses Enum keys.
The Context
provided to .getSharedPreferences()
is only there to let the system access your application-specific information; every Activity
in your app shares the same preferences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With