Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a sharedPreferences key value before attachBaseContext called?

My aim is overriding application language before it creates context and i'll use that context for calling other activities. Its possible via colling "recreate()" method on "onCreate" but i dont want to recreate activity to achive that goal. E.g

@Override
protected void attachBaseContext(Context newBase) {

    //null exception here
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    String langKey = getString(R.string.pref_language_key);
    String langValue = sharedPreferences.getString(langKey, null);

    super.attachBaseContext(ConfigurationUtil.wrapLanguage(newBase, langValue));
}

If this is not possible, any ideas how to set application language that user have choosen from settings?

like image 566
Ali Karaca Avatar asked Oct 14 '25 08:10

Ali Karaca


1 Answers

This worked for me:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(newBase);

please use newBase context and not your Activity context

like image 151
mroca Avatar answered Oct 17 '25 23:10

mroca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!