Search code examples
androidkotlinandroid-preferences

How to pass data between two PreferenceFragmentCompat classes?


I want to pass data like id to another PreferenceFragmentCompat class so that I could configure that specific group with the group id. In order to navigate between 2 Preference fragments you specify app:fragment in the preferences xml file or via code and set the arguments:

val bundle = Bundle()
bundle.putString("id", "group id")

val preference = Preference(context).apply {
    title = "group name"
    key = "key"
    fragment ="io.foodless.fragments.preferences.GroupPreference"
    arguments = bundle
}

But in the GroupPreference class When I try to access the argument id returns null

class GroupPreference:PreferenceFragmentCompat() {
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.group_preference,rootKey)

        val groupId = arguments?.getString("id")
        Log.d("debug","data $groupId")
    }
}

Solution

  • In Preference.getExtras() it says

    Return the extras Bundle object associated with this preference, creating a new Bundle if there currently isn't one. You can use this to get and set individual extra key/value pairs.

    So instead of making a new Bundle I called preference.getExtras() and it worked:

    val preference = Preference(context).apply {
        title = "group name"
        key = "key"
        fragment ="io.foodless.fragments.preferences.GroupPreference"
    
        val bundle = extras
        bundle.putString("id", "group id")
    }