Skip to content Skip to sidebar Skip to footer

How To Get Listpreference Value In Kotlin Activity

How can I get ListPreference value of selected option in my activity? Code root_preferences.xml &l

Solution 1:

After search 1 day, got solution.
1. 
<ListPreferenceapp:key="@string/keylist_preference"app:title="@string/title_list_preference"app:summary="%s"app:entries="@array/entries"app:entryValues="@array/entry_values"app:dialogTitle="@string/dialog_title_list_preference"/>

 2. <resources>
    <string-arrayname="entries"><item>SIT1-8143</item><item>SIT2-8243</item><item>SIT3-8343</item><item>SIT4-8443</item><item>SIT5-8543</item><item>SIT6-8643</item></string-array><string-arrayname="entry_values"><item>https://172.29.226.197:8143</item><item>https://172.29.226.197:8243</item><item>https://172.29.226.197:8343</item><item>https://172.29.226.197:8443</item><item>https://172.29.226.197:8543</item><item>https://172.29.226.197:8643</item></string-array>3. 
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.dialogs, rootKey)

            val listPreference = findPreference<Preference>(getString(R.string.keylist_preference)) asListPreference?
            listPreference?.setOnPreferenceChangeListener { preference, newValue ->
                if (preference is ListPreference) {
                    val index = preference.findIndexOfValue(newValue.toString())
                    val entry = preference.entries.get(index)
                    val entryvalue = preference.entryValues.get(index)
                    Log.i("selected val", " position - $index value - $entry, entryvalue - $entryvalue ")
                }

                true
            }
        }

Solution 2:

Update: I've designed a solution using DialogFragment:

classLanguageListFragment : DialogFragment() {

        overridefunonCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.select_language, container, false)
        }

        overridefunonViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)

            val radioGroup = view.findViewById<RadioGroup>(R.id.lang_radio_group)
            radioGroup.setOnCheckedChangeListener { group, checkedId ->
                when (checkedId) {
                    R.id.ar -> {
                        languageSaved("ar")
                    }
                    R.id.bh -> {
                        languageSaved("bh")
                    }
                    R.id.en -> {
                        languageSaved("en")
                    }
                    //add more if needed..
                }
            }
        }

        funlanguageSaved(languageCode: String) {
            val myPref: PrefManager = PrefManager(context!!)
            myPref.language = languageCode

            Toast.makeText(
                activity, "Clicked: Bhasa", Toast.LENGTH_SHORT
            ).show()

            // reset the activity
            ActivityCompat.finishAffinity(activity!!)
            startActivity(Intent(activity!!, MainActivity::class.java))
        }
    }

View of your fragment:

<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"><RadioGroupandroid:id="@+id/lang_radio_group"android:layout_width="161dp"android:layout_height="118dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.184"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintVertical_bias="0.137"><RadioButtonandroid:id="@+id/ar"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Arabic" /><RadioButtonandroid:id="@+id/bh"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Bhasa" /><RadioButtonandroid:id="@+id/en"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="English" /></RadioGroup></androidx.constraintlayout.widget.ConstraintLayout>

Use this PrefManager instead of previous one:

classPrefManager(privateval mContext: Context) {

    privatevar editor: SharedPreferences.Editor? = nullprivatevar prefs: SharedPreferences? = nullprivateval LANGUAGE = "language"privateval PREF = "user_info"var language: String?
        get() {
            this.prefs = this.mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE)
            returnthis.prefs!!.getString(LANGUAGE, "en")
        }
        set(language) {
            this.editor = this.mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit()
            this.editor!!.putString(LANGUAGE, language)
            this.editor!!.apply()
        }
}

End of update

You need to set up a correct listener for your SharedPref. so we'll use a helper method to register the listener. and then register using the activity or fragment where you want your callback to be called at any change to your SharedPref..

Setting up correct listener: (you may use anonymous listener also..)

import android.content.Context
import android.content.SharedPreferences
import android.util.Log

classPrefManager(privateval mContext: Context) {

    privatevar editor: SharedPreferences.Editor? = nullprivatevar prefs: SharedPreferences? = nullprivateval LANGUAGE = "language"privateval PREF = "user_info"var language: String?
        get() {
            returnthis.prefs!!.getString(LANGUAGE, "en")
        }
        set(language) {
            this.editor = this.mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit()
            this.editor!!.putString(LANGUAGE, language)
            this.editor!!.apply()
            Log.d("TAG", "Should be saved")
        }

    funregListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
        this.prefs = this.mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE)
        /*this.prefs!!.registerOnSharedPreferenceChangeListener { sharedPreferences: SharedPreferences, s: String ->
            Log.d("TAG", "Listener Fired: $s")
        }*/this.prefs!!.registerOnSharedPreferenceChangeListener(listener)

    }

}

Now register your activity where value is needed:

classMainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {

    overridefunonCreate(savedInstanceState: Bundle?) {
//        val wordViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val myPref = PrefManager(this)
        myPref.regListener(this)

        myPref.language = "en"
        myPref.language = "bn"
        myPref.language = "ar"
    }

    overridefunonSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        val firedWithValue = sharedPreferences!!.getString(key, "default value")
        Log.d("TAG", "Fired Pref. $firedWithValue")
    }
}

Now as we pass this as the listener and implement OnSharedPreferenceChangeListener our acticvity's OnSharedPreferenceChangeListener() method will be called each time the language value is set

Post a Comment for "How To Get Listpreference Value In Kotlin Activity"