Recently, while developing a new application on Android, I face with weird ‘ClassCastException’ messages. I was initially confused by these messages. While most of the time, these messages are logical and are due to programming mistakes due to copy-and-paste, these errors can also occur due to the file R.java that is generated automatically by Android.
As you might be aware, R.java contains integer IDs for each resource used to develop and Android application. The Android SDK automatically generates these numbers for us. This automatic generation can sometimes lead to headaches, particularly when you end up making changes to layouts. So, if you remove UI elements from a layout and replace them by some other elements, it can happen that the R.java file is not updated properly. Hence it continues to hold IDs for resources that might not exist anymore OR for resources whose type has changed. So what happens is that you have specified R.id.X and expect the ID to represent a Button UI control. Because we changed the layout and replaced the button by a TextView and R.java was not updated properly, R.id.X continues to indicate a Button, while in reality it is a TextView.
To be very sure, make it a point to clean the project each time you change the layout. Alternately, you can also delete R.java manually and have it re-created.