android.app.Application无法强制转换为android.app.Activity

Dom*_*WTF 31 java android classcastexception android-activity

我正在尝试LinearLayout从另一个类更改一个,但是当我运行此代码时:

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);
}
Run Code Online (Sandbox Code Playgroud)

我得到了 ClassCastException

context是Activity使用getApplicationContext()传递的main活动;

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)
Run Code Online (Sandbox Code Playgroud)

cod*_*gic 98

您正在传递应用程序Context而不是Activity Context使用

getApplicationContext();
Run Code Online (Sandbox Code Playgroud)

无论你在哪里通过它this或通过ActivityName.this.

既然你想投的Context传递(如你想申请不活动)到Activity

(Activity)
Run Code Online (Sandbox Code Playgroud)

你得到这个例外,因为你不能将应用程序转换为应用程序,Activity因为Application不是子类Activity.

  • 这是一个答案?与日志相同,但有很多行“ClassCastException: android.app.Application cannot be cast to android.app.Activity” 对我来说一个解决方案是使用 Activity 中的“this” (2认同)
  • 拯救了我们所有人。谢谢你! (2认同)

小智 5

如果您的项目使用匕首,然后出现此错误,您可以将其添加到 android manifest

   <application
        ...
        android: name = ".BaseApplication"
        ...> ...
Run Code Online (Sandbox Code Playgroud)

  • 我没有使用匕首,但它对我有用。谢谢 (3认同)