自定义全局 Application 类中断为“ android.app. Application can not be cast to”

我有一个定制的全局类,它看起来像这样

import android.app.Application;


public class MyApp extends Application {


public String MainAct;


public String getMainAct() {
return MainAct;
}


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

我想通过 onCreate方法中的另一个 Activity来保留这个类中的字符串。

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

它在标记的行上中断,并出现错误: Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.xxx.yyy.global.MyApp

我已经检查代码五次了,我找不到任何错误。有人能告诉我错误在哪里吗!

谢谢

75654 次浏览

错误指出 getApplication返回的对象的类型是 android.app.Application。一个可能的原因是您未能在清单中定义应用程序。确保你的清单中包括以下内容:

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

旧的 Android 设备或模拟器的另一种解决方案。 您在清单中定义了一个应用程序:

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

但你还有这个问题?

尝试禁用即时运行:

  1. 禁用即时运行
  2. 清理和重建项目
  3. 从设备中删除应用程序并重新安装,不需要即时运行