Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to use SharedPreferences in non-Activity class?

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().

like image 443
Jake Wilson Avatar asked Sep 20 '11 20:09

Jake Wilson


People also ask

Can we use SharedPreferences in fragment?

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).

Can we use SharedPreferences in Android?

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.

Is SQLite better than SharedPreferences?

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.

How do you use SharedPreferences in Android to store fetch and edit values?

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.


2 Answers

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); 
like image 152
Sandor Avatar answered Sep 17 '22 20:09

Sandor


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.

like image 37
Santi Avatar answered Sep 17 '22 20:09

Santi