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

浪尽此生 提交于 2019-12-27 22:07:26

问题


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)

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23546303/android-app-application-cannot-be-cast-to-android-app-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!