Search code examples
androidkotlinsharedpreferencesandroidx

How to use custom SharedPreferences name with AndroidX Preferences Library?


I'm using SharedPreferences with a custom SharedPreferences-names in my project, unfortunately the AndroidX Preferences Library seems not to be able to deal with it.

Using this library to create my Settings Activity / Fragment will always get / set SharedPreferences in the Default SharedPreferences - is there any way to pass my SharedPreferences names to actually access / edit the data in those different instances? Thank you very much.


Solution

  • If you want to use specific SharedPreferences on your settings screen, you can call this right before you call setPreferencesFromResource() in onCreatePreferences():

    preferenceManager.sharedPreferencesName = "mySpecificPreferences"
    preferenceManager.sharedPreferencesMode = Context.MODE_PRIVATE