0

I have a main menu activity with a bunch of buttons. One button starts a new activity that allows the user to fill out and submit a form. When the user submits the form, a third activity starts, basically just a screen with some content and a button to return to the main menu. However, when I create an intent and go to the main activity, setContentView() is not working and my button assignments cause a NullPointerException.

I know there is some way to go back in the stack, either via intent flags or calling finish(). I haven't had success with intent flags such as Intent.FLAG_ACTIVITY_CLEAR_TOP. finish() will not work since I am two activities away, not one. What is the proper way of getting back to the main activity?

Thanks

Nikhil
  • 16,194
  • 20
  • 64
  • 81
DuFF14
  • 15
  • 5

4 Answers4

6

There a bunch of ways you could do this. The easiest may be calling finish() on the second activity after it launches the intent, something like this:

startActivity(activity3intent);
finish();

This will remove your second activity from the stack as the third one starts. Then, your MainMenu button can just call finish on the third activity, returning you to the first.

If you'd prefer to do it with Intent Flags, try adding this to the Intent that calls Activity 1 from Activity 3:

activity1intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

This will bring Activity 1 back into focus and clear anything that was above it on the Stack. The CLEAR_TOP flag handles getting rid of the rest of the stack, but IIRC, will not start a new instance of the Activity if it already exists on the stack. If you'd rather start a new instance of Activity 1, don't use any flags, but call finish() after both activity 2 and 3 have sent their intents, so that they can't be accessed through back navigation.

MattDavis
  • 5,158
  • 2
  • 23
  • 35
0

In activity 2, if you call startActivity(yourIntent); finish() it should allow you to go back to Activity 1 when Activity 3 finishes.

Nate
  • 401
  • 2
  • 7
0

If user fill out and submit your form try to close your activity by calling finish() method in listener of button that submits form.

ghost
  • 87
  • 1
  • 9
0

You may also create a static class containing all activities so you can properly handle them. This is both extremely useful and extremely inefficient, but whatever.

Charlie-Blake
  • 10,832
  • 13
  • 55
  • 90