I try to use SharedPreferences, but I don't understand why we need the context.
If I create a SharedPreferences with the context of my main activity, can I get something with another context?
For example with an intentService class
Thanks
I try to use SharedPreferences, but I don't understand why we need the context.
If I create a SharedPreferences with the context of my main activity, can I get something with another context?
For example with an intentService class
Thanks
An IntentService
is a subclass of Context
(just as are Activity
, Application
, and many other Android classes). So of course you can create a SharedPreferences
from an IntentService
. It will see the same SharedPreferences
values that any Activity
or other Context
in your application would see. (That's why it's called shared.) You just have to make sure that you apply()
or commit()
changes made in the preference's editor in one context for the changes to be seen in other places. This is all covered in the docs.
The SharedPreferences are read and saved to disk.
Therefore the class needs to know where the app is located - and the only way to know that is thru a Context.
In standard Java there are global (static) objects, so you can do like for example System.getProperty("user.home") to access the user's home directory. That systems isnt maintained in Android - in Android you need to use the Context to get to the home dir of the app
Looking at the Android Source Code. You would get to know that Context class internally maintains a static HashMap of shared preferences for quick access:
private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs =
new HashMap<String, SharedPreferencesImpl>();
So you can get SharedPreferences from any class like Intent Service
or Activity
etc which extends Context
and it will always return the same object if given the same name.
Note: IntentService
does extend Context if you trace the chain:
IntentService extends Service
Service extends ContextWrapper
ContextWrapper extends Context
Yes, This is non sense question,but anyway. As you know about SharedPreference.It is used to Store private primitive data.
Here,on private data term. This means this data is stored to your application's storage path. Which is data/data/yourpackageName/shared_prefs
.
So To access your application's storage, SharePreference
needs your active context of any running Activity
.