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