Android : Cannot cast from View to Button

14,927

Solution 1

try this,

android.widget.Button myButton = (android.widget.Button)findViewById(R.id.my_button); 

Solution 2

Is the exception a ClassCastException? If so then the view you are finding with the id my_button isn't a button. If it's a NullPointerException then there is no view with the id my_button. This could be cause by not calling setContent() before you try to find the views.

Solution 3

I too have encountered this error and was unable to find a reason why it was happening. Like Joe Plante points out if it isn't working then something is wrong....

In my scenario I happened to give the Relative Layout an id (ie clicking in a blank space in the graphical layout) the same ID as my button. This was causing the wrong View to be returned by FindViewById(R.id.my_button);

To check this in your xml see if the

<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btnRecipe"

Solution 4

My guess is that your XML view (my_button) is not a button. Otherwise, are you sure that the id for your button is correct? It should read like "android:id="@+id/my_button"" as well as having a width and a height. Please post your XML file.

Solution 5

I actually encountered this in code I was doing. Basically it was the "If it looks like a duck and if it sounds like a duck, then why the bloody insert expletive here aren't you seeing it as a duck?" situation. I changed the equivalent of android:id="@+id/someid" by changing it to equivalent of android:id="@+id/someid_x" (don't forget to do this in Java as well) and everything worked like clockwork again.

So, in my situation, I believe that there might have been an ID out there referencing another object in the R table, and it was getting the wrong or unintended item. The strangest thing is that it started to happen when put a set of views into a RelativeLayout

Share:
14,927
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin over 1 year

    I just started working with the Android, but seem to have come across a problem that I simply can't find the answer to. I get the error "Cannot cast from View to Button" on this line :

    Button myButton = (Button)findViewById(R.id.my_button);
    

    I've tried many different things to get it going, and I've searched for the answer, but for some reason it just refuses to work right. If anybody could point me in the right direction it'd be most appreciated.

    Thank in advance.