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...

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
OppfinnarJocke
  • 1,038
  • 2
  • 9
  • 21
  • please could you add also your main.xml file? It seems that you are trying to cast a Button as a ProgressBar. – Ivan Jan 06 '12 at 14:06
  • 1
    No, I'm not, not consciously at least (see the post). It was the R.java that did not get updated, see below. – OppfinnarJocke Jan 06 '12 at 15:34
  • 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). – Ivan Jan 06 '12 at 18:14

2 Answers2

20

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

sebastianf182
  • 9,844
  • 3
  • 34
  • 66
  • 1
    +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"... – Richard Le Mesurier Jan 06 '12 at 14:59
  • 1
    Excellent. Please consider accepting the answer so it doesn't remain unanswered. – sebastianf182 Jan 06 '12 at 17:31
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.

Kamchatka
  • 3,597
  • 4
  • 38
  • 69