Returning to the parent activity

I recently had to resolve a bug in one of my projects where if the user pressed the back button in the Toolbar to go back to the previous screen, the app would crash.

And the app would crash because the previous screen was supposed to be displaying a data that was passed from the screen before that, and the activity would for some reason lose reference to the variable that was supposed to represent that data. To illustrate what I was experiencing, the flow went something like this.

Screen A -> Screen B -> Screen C

Let’s say the app is a cupcake ordering app. Screen A displays a list of cupcakes. User clicks on one cupcake and we display the single cupcake in Screen B. User clicks “Order Cupcake” which takes the user to Screen C. The user decides he/she does not want the cupcake and presses the back icon in the Toolbar.

Note: the bug does not occur if the user presses the Android’s native back button, the one on the bottom of the phone that’s native to the OS.

Once the user clicks the back icon in the Toolbar, the variable that represents the cupcake in Screen B will become null and it would cause the dreaded NullPointerException.

Clicking that in Screen C would crash the app in Screen B with the NullPointerException

And the code in Screen B looked something like this.

And in that code, mCupcake would become null and cause all sorts of NullPointerExceptions.

Now, why was this happening? It turns out that it’s due to the way I declared my activities in my AndroidManifest. In my AndroidManifest, I had declared my three activities like this.

It looks “correct” but it turns out the reason I was having the crashes with NullPointerException‘s was due to missing the android:launchMode="singleTop" in each of the activity declaration.

For example, each declaration should have looked like

Why is the launchMode option so important? It turns out that the standard launchMode (meaning if you don’t put one in), causes Android to always recreates the activity (calling onCreate) even if the task stack (parentActivityName declaration) is handled correctly. To prevent this, you need to add the launchMode="singleTop" declaration to your activities.

The link to the documentation is

https://developer.android.com/guide/topics/manifest/activity-element.html#lmode

For some reason, I think the default configuration should be to have the launchMode set to singleTop when the user presses back into the previous activity, rather than recreating the activity entirely. I can’t think of a single app that I use where I expect pressing the back button on the Toolbar to behave differently than when I press the Android OS’s back button.

About the Author Chris Jeon

Software developer currently focusing on Android development.