How to override configuration in Android application?
Asked Answered
M

2

5

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());
}
Mckown answered 4/3, 2018 at 14:0 Comment(0)
M
9

Solution (override protected method attachBaseContext)

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(newBase);
    // copypaste safe code
    applyOverrideConfiguration(new Configuration());
}
Mckown answered 4/3, 2018 at 14:56 Comment(1)
Thanks! This solution helped me solve an issue where changing language was not working in Android 7 & below, after implementing Dagger Hilt.Lemus
A
-1

Upgrading to appcompat 1.2.0 solves the issue with java.lang.IllegalStateException: getResources() has already been called. Replace the appcompat dependency app level build.gradle with this

dependencies {
   implementation 'androidx.appcompat:appcompat:1.2.0'
}
Apple answered 7/10, 2020 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.