Search code examples
javaandroidkotlinsaveonchange

How to save selected language, after closing and reopening the Application?


I want to change the language of the program and exit the program, and after re-entering the program, the original language of the device can not change the language selected by the program. if there is any way please help me at this point. here is my codes :

class LanguageActivity : AppCompatActivity() {
private lateinit var databinding: ActivityLanguageBinding
private lateinit var locale: Locale
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    databinding = DataBindingUtil.setContentView(this,R.layout.activity_language)
    val languageList = ArrayList<String>()
    languageList.add("Select")
    languageList.add("English")
    languageList.add("Persian")
    languageList.add("Pashto")
    val adapter = ArrayAdapter(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, languageList)
    databinding.spinnerLanguage.adapter = adapter
    databinding.spinnerLanguage.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            when(position){
                0 -> {
                }
                1 -> setLocale("en")
                2 -> setLocale("fa")
                3 -> setLocale("ps")
            }
        }
        override fun onNothingSelected(parent: AdapterView<*>?) {
        }
    }
}
fun setLocale (languageName: String){
    locale = Locale(languageName)
    val res = resources
    val dm = res.displayMetrics
    val conf = res.configuration
    conf.locale = locale
    res.updateConfiguration(conf,dm)
    val refresh = Intent(this, LanguageActivity::class.java)
    startActivity(refresh)
}

my project does not have even 1 error, but the thing that I want is in too many apps by changing language inside them and they keep selected language, but mine after closing and reopennig, the selected language is changed by default device language!

changing onCreate() to onResume() and onStop() as the lifecycle changed nothing in my app. thanks a lot to whom is trying to help me :)


Solution

    1. You can store the value (selected language) in SharedPreference
    2. and then in onStop() you can store the value in database
    3. and then in onStart() you can read the value from database and keep in SharedPreference