Java – is there any way to make SharedPreferences global in my entire Android application?

Is there any way to make SharedPreferences global in my entire application? Now I use these lines in many parts of the code to store simple on / off settings for some preferences that users can set I just want to call once around the world as much as possible:

SharedPreferences settings = getSharedPreferences("prefs",0);
SharedPreferences.Editor editor = settings.edit();

Any hint about how to call these rows in all classes will be great:

editor.putString("examplesetting","off");
editor.commit();

and

String checkedSetting = settings.getString("examplesetting","");

Solution

I know, I know, I'll get inflamed and throw myself into the embers of hell

Use a singleton class that surrounds sharedpreference settings, as follows:

public class PrefSingleton{
   private static PrefSingleton mInstance;
   private Context mContext;
   //
   private SharedPreferences mMyPreferences;

   private PrefSingleton(){ }

   public static PrefSingleton getInstance(){
       if (mInstance == null) mInstance = new PrefSingleton();
       return mInstance;
   }

   public void Initialize(Context ctxt){
       mContext = ctxt;
       //
       mMyPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
   }
}

And create wrapper functions around what your example represents in the question, for example,

PrefSingleton. getInstance(). writePreference(“exampleSetting”,“off”);

And the implementation may be as follows:

// Within Singleton class

public void writePreference(String key,String value){
     Editor e = mMyPreference.edit();
     e.putString(key,value);
     e.commit();
}

From your first activity, activate the bachelor class in such a way as:

PrefSingleton.getInstance().Initialize(getApplicationContext());

I ventured to vote because using global static classes may be a bad idea, contrary to basic programming practices However, in addition to this nitpick, it will ensure that only the only object in the prefsingleton class can exist and be accessed, regardless of the activity of the code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>