Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changed order in main.xml, now I get ClassCastException

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

like image 751
OppfinnarJocke Avatar asked Jan 06 '12 13:01

OppfinnarJocke


2 Answers

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

like image 59
sebastianf182 Avatar answered Oct 29 '22 09:10

sebastianf182


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.

like image 32
Kamchatka Avatar answered Oct 29 '22 09:10

Kamchatka