简体   繁体   English

无法将申请转换为课程

[英]Cannot cast Application to Class

i have the following class: 我有以下课程:

    public class Mediator extends Application
{
    private HTTPSender sender;

    public Mediator()
    {
        sender = new HTTPSender();
    }

    public void sendMessage()
    {

    }
}

Now in my activity i do the following: 现在在我的活动中,请执行以下操作:

public class Contact extends ActionBarActivity {
    private Mediator mediator;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.mediator = (Mediator) getApplication();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }
}

When i run my application i get the following: 当我运行我的应用程序时,我得到以下信息:

  Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to dk.AnApp.app.Mediator

Can anyone tell me why i am unable to cast it to a class that extends application? 谁能告诉我为什么我无法将其转换为扩展应用程序的类?

In your manifest you should declare that Mediator is the application class so it gets instantiated as the application. 在清单中,您应该声明Mediatorapplication类,以便将其实例化为应用程序。

For example, 例如,

<application
    android:name="dk.AnApp.app.Mediator"
    ...

Reference 参考

This takes care of the exception but does not guarantee that your Mediator class exists for a good reason (as CommonsWare points out in comments). 这可以处理异常,但不能保证您的Mediator类存在充分的理由(如CommonsWare在注释中指出的那样)。

this.mediator = (Mediator) getApplication();

I think that this is your issue. 我认为这是您的问题。 getApplication() is returning an Application which is a super class of Mediator and so you can not cast down the inheritance tree like this. getApplication()返回的ApplicationMediator的超类,因此您不能像这样丢弃继承树。

<application 
    android:label="@string/app_name" 
    android:icon="@drawable/ic_launcher" 
    android:name="ThisApplicationClass" // Here
    >

Adding a android:name attribute into your application element in your manifest file (as above) can get the Android API to return the correct class type for you. 在清单文件(如上所述)中的application元素中添加android:name属性可以获取Android API来为您返回正确的类类型。

I have performed: 我已经执行了:

this.mediator = (Mediator)getApplication()

and it worked! 而且有效! I did have my Manifest ok, also extends Application in the other class. 我确实可以执行清单,也可以在其他课程中扩展Application。 But I still had this cast issue. 但是我仍然有这个演员表问题。 Fortunately, I could resolve it! 幸运的是,我可以解决它! :D Thanks! :D谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM