Not able to use dagger-injected objects in attachB

2019-07-11 03:54发布

问题:

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 already inside appModule when I try to use this LocaleManager instance inside attachBaseContext I get null pointer exception as the activity's injections happen after attachBaseContext inside onCreate().

回答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:

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(new LocaleManager(base).updateContext());
}

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

public Context updateContext() {
    Locale locale = new Locale(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) {
    Resources resources = mContext.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    return mContext;
}


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