akexorcist / Localization

[Android] In-app language changing library
Apache License 2.0
983 stars 154 forks source link

App is crashing in LocalizationApplication getApplicationContext() #95

Closed ashutoshgohil closed 3 years ago

ashutoshgohil commented 3 years ago

Hi found below issue in some devices, can you please help me to get it resolve. I have mentioned error below

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:118) at com.LocalizationApplication.getApplicationContext(LocalizationApplication.java:23)

akexorcist commented 3 years ago

Hi @ashutoshgohil

Where did you put the getApplicationContext() in your code?

ashutoshgohil commented 3 years ago
abstract class LocalizationApplication : Application() {
    private val localizationDelegate = LocalizationApplicationDelegate()

    override fun attachBaseContext(base: Context) {
        localizationDelegate.setDefaultLanguage(base, getDefaultLanguage())
        super.attachBaseContext(localizationDelegate.attachBaseContext(base))
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        localizationDelegate.onConfigurationChanged(this)
    }

    override fun getApplicationContext(): Context {
        return localizationDelegate.getApplicationContext(super.getApplicationContext())
    }

    abstract fun getDefaultLanguage(): Locale
}
akexorcist commented 3 years ago

@ashutoshgohil Is there any more getApplicationContext() invoke in your code?. And could you provide the full stack trace. 3 lines of stack trace doesn't enough to determine the cause of problem.

akexorcist commented 3 years ago

@ashutoshgohil 1.2.8 in coming, please check it out. it might solve this problem (Refer to #97).

akexorcist commented 3 years ago

@ashutoshgohil It's my fault. I forget to put the override fun getResources(): Resources in README.md

For the application delegation you need to add getResources(): Resources as override method as below

// LocalizationApplication.kt
override fun getResources(): Resources {
    return localizationDelegate.getResources(this)
}