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?

Answers


In your manifest you should declare that Mediator is the application class so it gets instantiated as the application.

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).


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.

<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.


I have performed:

this.mediator = (Mediator)getApplication()

and it worked! I did have my Manifest ok, also extends Application in the other class. But I still had this cast issue. Fortunately, I could resolve it! :D Thanks!


Need Your Help

get count of facebook likes with SDK api()

javascript facebook facebook-graph-api

I know there is a way to get the number of facebook likes using this approach:

.NET: Why does this domain not resolve?

c# .net dns

I am trying to programmatically test if a given domain name exists.