Search code examples
javaandroidkotlinnullpointerexceptionlocale

Changing locale in MainActivity works, but changing it in Fragment gives Nullpointerexception


I have a ListPreference which I want to use to change the language of my app.

    <ListPreference
        android:key="@string/language_preference"
        android:title="@string/preference_title"
        android:entries="@array/language_array"
        android:entryValues="@array/language_data"
        app:iconSpaceReserved="false" />

I'm using this localization library to help. In my MainActivity I have two functions to change the (currently) two supported languages:

    fun changeLanguageGer() {
        setLanguage("de")
    }

    fun changeLanguageEn() {
        setLanguage("en")
    }

I happen to have a spinner in my MainActivity that I "misused" to check if those methods work: When changing to the according spinner item my app language changes as expected.

But I actually want to make this change in my settings with the ListPreference.

In the SettingsFragment I have the following code:

class SettingsActivity : LocalizationActivity() {

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

            // language
            val listPreference =
                findPreference<Preference>(getString(R.string.language_preference)) as ListPreference?
            listPreference?.setOnPreferenceChangeListener { preference, newValue ->
                if (preference is ListPreference) {
                    val index = preference.findIndexOfValue(newValue.toString())
                    val locale = preference.entryValues[index]
                    if (locale == "de") {
                        Toast.makeText(activity,locale, Toast.LENGTH_LONG).show()
                        MainActivity().changeLanguageGer()
                    }
                    if (locale == "en") {
                        Toast.makeText(activity,locale, Toast.LENGTH_LONG).show()
                        MainActivity().changeLanguageEn()
                    }
                }
                true
            }
        }
    }
}

This gives me the following Nullpointerexception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference. I added the toast statements to make sure the output I get when clicking on the language I want to change to is correct, which it is (either gives me "de" or "en").

How would I go about debugging this?


Solution

  • (activity as SettingsActivity).changeLanguageEn()
    

    Try using this to change the language.