Search code examples
androidandroid-studiokotlinandroid-fragmentsandroidx

How to use PreferenceFragment settings in other fragments?


I have a PreferenceFragment that contains 1 setting. It is defined (and called) with the following code :

class SettingsFragment : PreferenceFragmentCompat() {

override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
    setPreferencesFromResource(R.xml.settings, rootKey);
            loadSettings()

}

private fun loadSettings() {
    val sp = PreferenceManager.getDefaultSharedPreferences(this.context)

    val safemode = sp.getBoolean("safemode", false)
}

}

The fragment pops up normally and everything is good, but I do not have good understanding of SharedPreferences (I tried reading tutorials but I couldn't get it).

How do I store and use the settings in other fragments?


Solution

  • Actually SharedPreferences is for store small data (preferred strings) in it. Technically it is XML file that save key value type of data. You can have your SharedPreferences as static and use it every where you want. To obtain shared preferences, use the following method In your Application/Activity/Fragment:

    SharedPreferences prefs = this.getSharedPreferences(
          "com.example.app.test", Context.MODE_PRIVATE);
    

    To read preferences:

    String dummyKey = "dummyKey";
    
    String l = prefs.getString(dummyKey, "default value"); 
    

    To edit and save preferences

    String dt = getSomeString();
    prefs.edit().putString(dummyKey, dt).apply();
    

    commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.

    apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.