自定义全局应用程序类因“android.app.Application 无法转换为”而中断

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10607392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:20:26  来源:igfitidea点击:

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

android

提问by sandalone

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 Activityin its onCreatemethod.

我想通过ActivityonCreate方法中的另一个保留此类中的字符串。

    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

它在标记的行上中断并出现错误: 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

谢谢

回答by K-ballo

The error states that the type of the object returned by getApplicationis 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:

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

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

回答by Val

Another solution for older Android devices or emulators. You defined an application in the manifest:

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

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

but you still have this problem?

但是你还有这个问题吗?

Try to disable instant run:

尝试禁用即时运行:

  1. Disable an Instant run
  2. Clean and rebuild the project
  3. Remove the app from device and install it again without Instant run
  1. 禁用即时运行
  2. 清理并重建项目
  3. 从设备中删除应用程序并重新安装,无需即时运行