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)
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
.
in case your project use dagger, and then this error show up you can add this at android manifest
<application
...
android: name = ".BaseApplication"
...> ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With