[ACCEPTED]-Accessing SharedPreferences through static methods-sharedpreferences

Accepted answer
Score: 67

Cristian's answer is good, but if you want 2 to be able to access your shared preferences 1 from everywhere the right way would be:

  1. Create a subclass of Application, e.g. public class MyApp extends Application {...
  2. Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name="MyApp" (so the class is recognized by Android)
  3. In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp(). You then can use this method later to get a context of your application and therefore get your shared preferences. :-)
Score: 36

That's because in this case, act is an object 7 that you just create. You have to let Android 6 do that for you; getSharedPreferences() is a method of Context, (Activity, Service and 5 other classes extends from Context). So, you have 4 to make your choice:

  • If the method is inside 3 an activity or other kind of context:

    getApplicationContext().getSharedPreferences("foo", 0);
    
  • If 2 the method is outside an activity or other 1 kind of context:

    // you have to pass the context to it. In your case:
    // this is inside a public class
    public static SharedPreferences getSharedPreferences (Context ctxt) {
       return ctxt.getSharedPreferences("FILE", 0);
    }
    
    // and, this is in your activity
    YourClass.this.getSharedPreferences(YourClass.this.getApplicationContext());
    
Score: 10

I had a similar problem and I solved it 12 by simply passing the current context to 11 the static function:

public static void LoadData(Context context)
{
    SharedPreferences SaveData = context.getSharedPreferences(FILENAME, MODE_PRIVATE);
    Variable = SaveData.getInt("Variable", 0);
    Variable1 = SaveData.getInt("Variable1", 0);
    Variable2 = SaveData.getInt("Variable2", 0);
}

Since you are calling 10 from outside of an activity, you'll need 9 to save the context:

public static Context context;

And inside OnCreate:

context = this;

Storing 8 the context as a static variable, can cause 7 problems because when the class is destroyed 6 so are the static variables. This sometimes 5 happens when the app is interrupted and 4 becomes low on memory. Just make sure that 3 the context is always set before you attempt 2 to use it even when the class setting the 1 context is randomly destroyed.

Score: 8

Here's a better alternative to storing your 2 shared preferences in static fields.

  1. Similar to what has been suggested here, create a class that extends Application
  2. Make the constructor for your class take Context as a parameter.
  3. Use your context to get shared preferences and store them in private variables.
  4. Create public variables to return the retrieved data.

e.g

public class UserInfo extends Application{
    private String SAVED_USERID;
    private String SAVED_USERNAME;

    public UserInfo(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(FILE, MODE_PRIVATE);
        SAVED_USERNAME = prefs.getString("UserName", null);
        SAVED_USERID = prefs.getString("UserID", null);
    }

    public String getSavedUserName() {
        return SAVED_USERNAME;
    }

    public String getSavedUserID() {
         return SAVED_USERID;
    }
}

usage 1 in your activity

   UserInfo user = new UserInfo(this.getApplicationContext());

   String SAVED_USERNAME = user.getSavedUserName();
   String SAVED_USERID = user.getSavedUserID();
Score: 2

I had the same need - some of my preferences 22 need to be accessed often, and efficiently. I 21 also imagine that reading and writing a 20 string from SharedPreferences is slightly 19 slower than getting and setting a static 18 variable (but likely to an insignificant 17 degree). I also just kind of got used to 16 using static fields, retrieving Preference 15 values only at startup, and saving them 14 on close.

I didn't love my options for keeping 13 static references to the SharedPreferences/contexts 12 directly, but so far this workaround has 11 sufficed.

My solution:

  1. Create a Settings class with all 10 the static variables you need.

  2. When the application 9 initializes, retrieve SharedPreferences 8 fields and immediately set all Settings 7 fields (I call a "loadSharedPrefs()" method 6 at the end of MainActivity's onCreate method).

  3. In 5 the SettingsActivity's preferenceChangeListener's 4 initialization, set the appropriate static 3 field in the Settings class. (I call a "setAppropriateSetting(key, value)" method 2 at the beginning of SettingsActivity's onPreferenceChange()).

Use 1 your static preferences wherever, whenever!

Score: 0
public static String getPreferenceValue(Context context) {
    SharedPreferences sharedPreferences = 
        PreferenceManager.getDefaultSharedPreferences(context);
    String key = context.getString(R.string.pref_key);
    String defaultVal = context.getString(R.string.pref_default);
    return sharedPreferences.getString(key,defaulVal);
}

0

More Related questions