Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SharedPreferences with different Contexts

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!

like image 236
SweSnow Avatar asked Dec 23 '12 17:12

SweSnow


People also ask

Can we use multiple SharedPreferences in Android?

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.

Can we store large amount of data in SharedPreferences?

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.

Is SQLite better than SharedPreferences?

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.

Is SharedPreferences Singleton?

There are 2 templates and samples: SharedPreferences Singleton that uses String keys. SharedPreferences Single that uses Enum keys.


1 Answers

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.

like image 73
Cat Avatar answered Nov 14 '22 10:11

Cat