0

i started creating a Android App with Android Studio. I created a button (and added android:onClick="page2") in the MainActivity that links to a second Activity with the following code in the MainActivity.java:

public void page2 (View view) {
    setContentView(R.layout.activity_page2);

}

So far that works well and i can change from the MainActivity to the page2 Activity. Now i tried to create a Button on page 2 to link back to the MainActivity, but when i start the emulator and click the button the app crashes..

Any suggestions what the problem is? Maybe i have to restart the MainActivity before i can switch back to it?

Thanks for the help :)

Jonas D
  • 11
  • 1
    You are not starting another activity here, only changing MainActivity's contentView. – Devrim Nov 04 '14 at 22:03
  • Ok, i get it, so is there an possibility to jump between 2 avtivitys via button press? – Jonas D Nov 04 '14 at 22:14
  • possible duplicate of [How to start new activity on button click](http://stackoverflow.com/questions/4186021/how-to-start-new-activity-on-button-click) – Devrim Nov 04 '14 at 22:19

2 Answers2

1

You aren't actually starting a new activity, which is why the app quits when you press back from the main activity. To start a new activity on button press implement the onClick method. Something like:

mButton.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View v)
    {
        Intent intent = new Intent(getActivity(), ActivityToStart.class);
        //intent.putExtra(...) depending on your needs
        startActivity(intent);
        //or startActivityForResult(...) depending on your needs
    }
}

View.OnClickListener

Starting Another Activity

pez
  • 3,859
  • 12
  • 40
  • 72
0

You should use an Intent

More information here : http://developer.android.com/training/basics/firstapp/starting-activity.html#BuildIntent

ToYonos
  • 16,469
  • 2
  • 54
  • 70