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,725
  • 9
  • 43
  • 75
B00527287
  • 1
  • 2
  • 2
    by On click, are you trying to load another xml? Or migrate to another activity? – ngrashia Aug 06 '14 at 10:04
  • Post your logcat. Are you getting NPE or what? – ngrashia Aug 06 '14 at 10:05
  • Unfortunately, the app has stopped is not enough to identify the problem you need to post exception details displayed in Android Monitor > logcat (in android studio) – Palak Mar 26 '16 at 06:29

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,345
  • 35
  • 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,786
  • 6
  • 31
  • 55
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,913
  • 8
  • 36
  • 64
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