Search code examples
javaandroidkotlinandroid-activityspinner

How to keep onItemSelected on the same item selected after closing the app in Kotlin?


i am translating an app in Kotlin and the user have the choice to choose between two different languages i created new Activity:

@Suppress("DEPRECATION")
class Languages_Activity : AppCompatActivity() {
lateinit var spinner: Spinner
lateinit var locale: Locale
var back_btn: LinearLayout? = null
private var currentLanguage = "en"
private var currentLang: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_languages_)
    title = "KotlinApp"
    currentLanguage = intent.getStringExtra(currentLang).toString()
    spinner = findViewById(R.id.spinner)
    val list = ArrayList<String>()
    list.add("Select Language")
    list.add("English")
    list.add("Malay")

    val adapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, list)
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    spinner.adapter = adapter
    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
            when (position) {
                0 -> {
                }
                1 -> setLocale("en")
                2 -> setLocale("my")

            }
        }
        override fun onNothingSelected(parent: AdapterView<*>) {}

    }
    back_btn = findViewById(R.id.back_btn_language)

    back_btn?.setOnClickListener {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    }
}
private fun setLocale(localeName: String) {
    if (localeName != currentLanguage) {
        locale = Locale(localeName)
        val res = resources
        val dm = res.displayMetrics
        val conf = res.configuration
        conf.locale = locale
        res.updateConfiguration(conf, dm)
        val refresh = Intent(
            this,
            Languages_Activity::class.java
        )
        refresh.putExtra(currentLang, localeName)
        startActivity(refresh)
    } else {
        Toast.makeText(
            this@Languages_Activity, "Language, , already, , selected)!", Toast.LENGTH_SHORT).show();
    }
}
override fun onBackPressed() {
    val intent = Intent(Intent.ACTION_MAIN)
    intent.addCategory(Intent.CATEGORY_HOME)
    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
    startActivity(intent)
    finish()
    exitProcess(0)
}
}

and when i choose a language the app will display the values of the chosen language but when i close the app and run it again it the choice will reset

how can i keep the item selected even after closing the app and run it again?


Solution

  • you can use shared preferences

    for this usecase.

    shared preferences are helpful when you want to store key-value pairs that can persist data across app close and open.

    this data will get deleted only when you clear your app data in settings or uninstall the app

    in your onCreate you can add this snippet

    val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
    val selectedLanguageIndex = sharedPref?.getInt("LANGUAGE_SELECTED", 0)?:0
    spinner.setSelection(selectedLanguageIndex)
    

    in your onItemSelected

    val sharedPref = requireActivity().getPreferences(Context.MODE_PRIVATE)
    with (sharedPref.edit()) {
        putInt("LANGUAGE_SELECTED", position)
        apply()
    }