Not able to use dagger-injected objects in attachBaseContext() to update locale

情到浓时终转凉″ 提交于 2019-12-10 23:39:09

问题


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);
}


来源:https://stackoverflow.com/questions/53277662/not-able-to-use-dagger-injected-objects-in-attachbasecontext-to-update-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!