Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 225
DomeWTF Avatar asked May 08 '14 15:05

DomeWTF


3 Answers

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.

like image 135
codeMagic Avatar answered Oct 14 '22 09:10

codeMagic


in case your project use dagger, and then this error show up you can add this at android manifest

   <application
        ...
        android: name = ".BaseApplication"
        ...> ...
like image 15
Tri yulianto Avatar answered Oct 14 '22 07:10

Tri yulianto


In my case, when I'm in an activity that extends from AppCompatActivity, it did not work(Activity) getApplicationContext (), I just putthis in its place.

like image 3
Gerrard Avatar answered Oct 14 '22 09:10

Gerrard