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

后端 未结 6 1151
梦如初夏
梦如初夏 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:22

    If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.

    Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.

    String preferencesName = this.getPreferenceManager().getSharedPreferencesName();
    

    The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.

提交回复
热议问题