Marc Rasmussen Marc Rasmussen - 4 years ago 124
Java Question

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download