Marc Rasmussen
Marc Rasmussen

Reputation: 20545

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?

Upvotes: 1

Views: 482

Answers (3)

Cecilia Barboza
Cecilia Barboza

Reputation: 117

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!

Upvotes: 0

Rudi Kershaw
Rudi Kershaw

Reputation: 12952

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.

Upvotes: 2

laalto
laalto

Reputation: 152787

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

Upvotes: 6

Related Questions