How do you use SharedPreferences in a non-Activity class? I tried making a generic Preferences utility class and importing android.content.Context
but Eclipse still wouldn't let me use getSharedPreferences()
.
The method getSharedPreferences is a method of the Context object, so just calling getSharedPreferences from a Fragment will not work... because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).
Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair.
With SQLite you use SQL language to create tables and then do insert, delete, update operations just like in any other database. But in case of shared preference you use just normal APIs provided by Android to write, read and update these values to a XML file.
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs. getString("text", null); if (restoredText != null) { String name = prefs. getString("name", "No name defined");//"No name defined" is the default value.
SharedPreferences are related to context. You can only reference it through a context.
You can simply pass context as a parameter to your class. For example in the constructor.
In your activity do:
MyClass myClass = new MyClass(this);
The solution i found to this was:
1-In an MainActivity class (i.e always launched before getting any context in project) create a static variable for the context:
public static Context contextOfApplication;
2-In an important method of this class (Such as onCreate, the constructor, etc) initialize this variable using the getApplicationContext method:
public void onCreate() { contextOfApplication = getApplicationContext(); }
3-In the same class Create a "getter" method for this variable (it must also be static):
public static Context getContextOfApplication(){ return contextOfApplication; }
4-In the non-activity class get the context by calling the created method statically:
Context applicationContext = MyActivityClass.getContextOfApplication()
;
5-Use the PreferenceManager Class to get the SharedPreferences variable:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
Hope it helps.
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