Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Keep previously added intent extra when going up to parent activity

Currently I am working with Android and I still have some troubles with understanding the Activity lifecycle.

Let me show you my problem with an example:

My App contains a Navigation Drawer which allows to use to switch between different Fragments. One Fragment (Fragment A) is a list with some items. Clicking one item opens activity B which can be described as a detail view of the item. B receives all necessary information by an Intent, the item model implements Parcelable and it is put as an Extra to the Intent. A button of Activity B opens the map view Activity C.

A -(Item)-> B -> C

Using the Up button in the action bar of C crashes the app when the B Activity onCreate method calls

Item item = bundle.getParcelable("com.example.myapp.model.Item");

Of course, because the detail view B gets all necessary information which has to be displayed from A. How can I solve that problem? I want to be able to store the item somehow when calling C and going up to B again. (Using the back button on C works fine)

like image 338
Daniel Avatar asked Aug 11 '14 10:08

Daniel


1 Answers

If you have implemented up navigation as described in Providing up navigation on the android developers site, you should be able to fix the error simply by changing the launch mode for activity B to "singleTop.". Set this in the application's manifest.xml file, as follows:

<activity ... launchMode="singleTop" ... />

What's happening now, presumably because B's launch mode is standard, is that up navigation is launching a new instance of activity B; it doesn't get the extras that were provided originally by A.

When the launch mode is "singleTop" according to the linked document,

If the parent activity has launch mode singleTop, or the up intent contains FLAG_ACTIVITY_CLEAR_TOP, the parent activity is brought to the top of the stack, and receives the intent through its onNewIntent() method.

In onNewIntent(), I believe (please check this), that you can just ignore the new intent, because you want to continue using the intent from activity A.

like image 71
x-code Avatar answered Oct 17 '22 23:10

x-code