0

I am a newbie to android development, trying to get buttons working. every time i use this code below, the error message "unfortunately the app has stopped". but when i remove the code the app runs but obviously the buttons do nothing. here is the code ive tried

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    Button button1 = (Button) findViewById(R.id.ExerciseButton);
    button1.setOnClickListener (new View.OnClickListener(){


        public void onClick(View v) {
        setContentView(R.layout.exercises);

}

});
}
}

anybody able to help me out there? thanks

Prasanth S
  • 3,549
  • 8
  • 41
  • 73
B00527287
  • 1
  • 2

4 Answers4

1

Don't try to load another View in the current activity. Navigate to a new ExercisesActivity.
Use:

public void onClick(View v) {
    Intent intent = new Intent(ExercisesActivity.this, WcActivity.class);
    startActivity(intent);
}
userM1433372
  • 5,175
  • 34
  • 38
0

You can't call setContentView anymore after the view has loaded (which it obviously has to receive button clicks). Use a different approach, like showing and hiding views or using a ViewFlipper (see Calling setContentView() multiple times), using fragments (see Fragments) or starting a new activity.

Community
  • 1
  • 1
0101100101
  • 5,560
  • 5
  • 30
  • 51
0

Well, from your code, I see a couple of things:

I am usually familiar to using the onClickListener of the Button class if I want to use it for a button. Makes sense, doesn't it?

buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
        //Do stuff here
}

Second thing:

Start a new Activity (if that is what you want) by using an Intent:

Intent myIntent = new Intent(this, exercises.class);
startActivity(myIntent);
PKlumpp
  • 4,485
  • 7
  • 34
  • 60
0

You CAN absolutaly call setContentView on any event, even after the view has loaded I tried your code in a demo project and it is working fine. So, i think the error will be some where in your layout.(Let me know more if you need more help on this)

Nish8900
  • 92
  • 4