How do I get the SharedPreferences from a PreferenceActivity in Android?

后端 未结 6 1153
梦如初夏
梦如初夏 2020-11-22 11:28

I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks l

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 12:19

    having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...

    public class global {
        public static Activity globalContext = null;
    

    and set it in the main activity create

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
                global.sdcardPath,
                ""));
        super.onCreate(savedInstanceState);
    
        //Start 
        //Debug.startMethodTracing("appname.Trace1");
    
        global.globalContext = this;
    

    also all preference keys should be language independent, I'm shocked nobody has mentioned that.

    getText(R.string.yourPrefKeyName).toString()
    

    now call it very simply like this in one line of code

    global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);
    

提交回复
热议问题