Skip to content Skip to sidebar Skip to footer

Not Able To Use Dagger-injected Objects In Attachbasecontext() To Update Locale

I am using dagger and I have to update the locale in the attachBaseContext of the activity, I am keeping the locale update logic inside LocaleManager and LocaleManager instance is

Solution 1:

This is happening, as you said, because the injection is happening after attachBaseContext is called.

I'm actually not sure what the question is here, but I was facing the same problem, but unfortunately I could not solve it with dagger. I needed to create a new LocaleManager in the attachBaseContext like this:

@OverrideprotectedvoidattachBaseContext(Context base) {
    super.attachBaseContext(newLocaleManager(base).updateContext());
}

where updateContext returns the context with the updated locale, like this:

public Context updateContext() {
    Localelocale=newLocale(DESIRED_LANGUAGECODE);
    Locale.setDefault(locale);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return updateResourcesLocale(locale);
    }
    return updateResourcesLocaleLegacy(locale);
}


@SuppressWarnings("deprecation")private Context updateResourcesLocaleLegacy(Locale locale) {
    Resourcesresources= mContext.getResources();
    Configurationconfiguration= resources.getConfiguration();
    configuration.locale = locale;
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    return mContext;
}


@TargetApi(Build.VERSION_CODES.N)private Context updateResourcesLocale(Locale locale) {
    Configurationconfiguration= mContext.getResources().getConfiguration();
    configuration.setLocale(locale);
    return mContext.createConfigurationContext(configuration);
}

Solution 2:

The solution is to inject your object in the Application class so that it can be available as soon as the application gets start.

In your Application class (a class which extends Application)

/**
     * Request UserLanguageProvider here so it's initialized as soon as possible and can be used by
     * [LocaleStaticInjector]
     */@Inject
    lateinit var userLanguageProvider: UserLanguageProvider

In BaseActivity.kt

overridefunattachBaseContext(newBase: Context) {
            val context: Context =  LanguageContextWrapper.wrap(newBase, LocaleStaticInjector.userLanguageProvider)
            super.attachBaseContext(context)
        }

In my custom class:

/**
 * We use  a static object to inject the locale helper dependency because it's used  in
 * [BaseActivity#attachBaseContext] which is called before the activity is injected!!
 */object LocaleStaticInjector {
         lateinit var userLanguageProvider: UserLanguageProvider
    }

Post a Comment for "Not Able To Use Dagger-injected Objects In Attachbasecontext() To Update Locale"