sandalone sandalone - 1 month ago 12
Android Question

Custom global Application class breaks with "android.app.Application cannot be cast to"

I have a custom global class which looks like this

import android.app.Application;

public class MyApp extends Application {

public String MainAct;

public String getMainAct() {
return MainAct;
}

public void setMainAct(String mainAct) {
MainAct = mainAct;
}
}


I want to preserve a string in this class via another
Activity
in its
onCreate
method.

String local = "myLocalVariable";
((MyApp) getApplication()).setMainAct(local); //breaks here!!!
String name = ((MyApp) getApplication()).getMainAct();


It breaks on the marked line with error:
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.xxx.yyy.global.MyApp


I've checked the code for five times and I cannot find error anywhere. Can anyone tell me where the error is?!

Thanks

Answer

The error states that the type of the object returned by getApplication is android.app.Application. A possible cause for this is that you failed to define the application in the manifest. Make sure that your manifest includes something in the lines of:

<application android:name=".MyApp"...
</application>
Comments