Solved (solution at the bottom)
In my activity I need to read preferences and then override configuration. In constructor Context is not ready yet:
Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
In onCreate
it is too late:
java.lang.IllegalStateException: getResources() has already been called
Quote from ContextThemeWrapper documentation:
This [applyOverrideConfiguration] method can only be called once, and must be called before any calls to getResources() or getAssets() are made.
What is the right time and place to override configuration?
Code excerpt from my current working solution below.
class OverrideActivity extends AppCompatActivity {
// ...
private boolean __overrideConf = false;
@Override
public Resources getResources() {
if (!__overrideConf) {
// ...
// read shared preferences needs context
// ...
applyOverrideConfiguration(configuration);
__overrideConf = true;
}
return super.getResources();
}
}
Solution (override protected method attachBaseContext)
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
applyOverrideConfiguration(new Configuration());
}