android.app.Application cannot be cast to android.app.Activity

DomeWTF picture DomeWTF · May 8, 2014 · Viewed 117.7k times · Source

I'm trying to change a LinearLayout from another class, but when i run this code:

public class IRC extends PircBot {

ArrayList<String> channels;
ArrayList<Integer> userCount;
ArrayList<String> topics;

LinearLayout channelLayout;
Context context;

public IRC(Context ctx) {
    this.setName("xxxx");
    channels = new ArrayList<String>();
    userCount = new ArrayList<Integer>();
    topics = new ArrayList<String>();

    context = ctx;

    channelLayout = (LinearLayout) ((Activity) context).findViewById(R.id.channels);
}

i get a ClassCastException

context is the Main activity that extends Activity passed with a getApplicationContext();

LOGCAT

05-08 17:53:55.102    3736-3799/g.d.allinonechat E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-5357
java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
        at g.d.xxx.IRC.<init>(IRC.java:34)
        at g.d.xxx.MainActivity$1.run(MainActivity.java:49)
        at java.lang.Thread.run(Thread.java:856)

Answer

codeMagic picture codeMagic · May 8, 2014

You are passing the Application Context not the Activity Context with

getApplicationContext();

Wherever you are passing it pass this or ActivityName.this instead.

Since you are trying to cast the Context you pass (Application not Activity as you thought) to an Activity with

(Activity)

you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity.