akexorcist / Localization

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

java.lang.ClassCastException: android.app.ContextImpl in version 1.2.7 #94

Closed jonas-weinhardt closed 3 years ago

jonas-weinhardt commented 3 years ago

I have a simple App with just 2 Activities. One Is the Main Activity and the other is an Activity where the user can change the language. It gets opened when the user clicks a button on the Main Activity. Both Activities inherit from LocalizationActivity. After the language gets changed the LanguageChange Activity gets finished to return to the Main Activity.

setLanguage("en");
finish();

Than the onResume function in the MainActivity gets triggered where I try to convert the Application Context to my Application class (witch inherits from LocalizationApplication):

@Override
protected void onResume() {
    super.onResume();
     App app = (App)getApplicationContext(); <-- java.lang.ClassCastException occures here 
}

Is there a way to get the right context at this point or am i doing something wrong? Everything works by the way in version 1.2.6

akexorcist commented 3 years ago

If you want to access any method in application class. You can cast the class from getApplication() not getApplicationContext()

Java

@Override
protected void onResume() {
    super.onResume();
    App app = (App)getApplication();
}

Kotlin

override fun onResume() {
    super.onResume()
    val app: App = application as App
}
akexorcist commented 3 years ago

@jonas-weinhardt Are you using the LocalizationActivityDelegate? I'm so sorry because 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

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