UpmostScarab UpmostScarab - 3 months ago 17
Android Question

Unxepcted ClassCastException from findViewById

I have the following code in xml file:

<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id = "@+id/buttonsLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity = "center"
app:columnCount="4"
app:rowCount="4"
app:useDefaultMargins="false"
>
</android.support.v7.widget.GridLayout>


and I'm filling this GridLayout dynamicly so I'm trying to get the object with:

android.support.v7.widget.GridLayout gl =
(android.support.v7.widget.GridLayout)findViewById(R.id.buttonsLayout);


Which gives me the following error:

Caused by: java.lang.ClassCastException: android.support.v7.internal.widget.TintButton cannot be cast to android.support.v7.widget.GridLayout at com.education4all.mathcoach.TaskActivity.onCreate(TaskActivity.java:134)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2033)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104) 
at android.app.ActivityThread.access$600(ActivityThread.java:132) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4575) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) 
at dalvik.system.NativeStart.main(Native Method)


This is very strange because this code used to work and suddenly this error appears. Why could that be?

build_gradle:

apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion '21.1.2'
defaultConfig {
applicationId "com.education4all.mathcoach"
minSdkVersion 10
targetSdkVersion 22
versionName '1.0.2'
versionCode 4
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.android.support:gridlayout-v7:18.0.+'
}

Answer

Try to use a higher version of the support library, i.e.: com.android.support:appcompat-v7:22.+, clean and try to run the project.

You can also use the latest version of the GridLayout as well.