Changed order in main.xml, now I get ClassCastException
Asked Answered
S

2

9

Using eclipse and the Android SDK, I managed a simple test app with a Button and a ProgressBar. All runs fine, except I did't want the ProgressBar to move the Button, when the ProgressBar was made visible, so just for testing I changed the order that they are defined in the res/layout/main.xml file (which uses a LinearLayout). Compiling and running I then get a ClassCastException at the "final ProgressBar ..." line below.

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /* 01-06 14:37:39.590: E/AndroidRuntime(863): java.lang.RuntimeException: 
       java.lang.ClassCastException: android.widget.Button cannot be cast to
       android.widget.ProgressBar */
    final ProgressBar progressbar = (ProgressBar) findViewById(R.id.progressBar1); /* here */
    progressbar.setVisibility(ProgressBar.GONE);

    final Button exebutton = (Button)findViewById(R.id.button1);
    exebutton.setOnClickListener(new View.OnClickListener()
    // etc...

Now, I understand what the ClasCastException says and means, I just don't understand why it appears. I am not trying to cast a Button to a ProgressBar. I don't get it...

Scad answered 6/1, 2012 at 13:59 Comment(3)
please could you add also your main.xml file? It seems that you are trying to cast a Button as a ProgressBar.Meteorology
No, I'm not, not consciously at least (see the post). It was the R.java that did not get updated, see below.Scad
Try to cleanup and rebuild your project. And paste the main.xml file so we can check if there are other problems (try also to remove one object and add it again).Meteorology
P
20

Try cleaning the project so the R class gets generated again. Sometimes the values dont update.

Primula answered 6/1, 2012 at 14:52 Comment(2)
+1 for cleaning. The Android SDK can get "confused" at times - this is one of those. Its often best to clean when making changes to the XML files. Between Eclipse's default behaviour, and what the SDK does, I find the project often gets build or runtime errors. When in doubt, "clean"...Goebbels
Excellent. Please consider accepting the answer so it doesn't remain unanswered.Primula
P
6

It looks like this line:

final ProgressBar progressbar = (ProgressBar) findViewById(R.id.progressBar1); /* here */

is casting a Button to a progressbar.

This means that the findViewById returns the button for R.id.progressBar1.

Since you are saying you changed the order, this looks this id still corresponds to the button. This points to a problem with the generated file. I would do a Project/Clean.

Phosphor answered 6/1, 2012 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.