mAndroid
mAndroid

Reputation: 5177

Alternatives to finish() to remove an Activity from view.

At present I have a main Activity which has a number of buttons leading to other screens which will allow the user to build up a number of search criteria. The search criteria are passed back to the main activity via extras on the intent.

the sub activities are started with StartActivityForResult and then when the user has made a selection I call finish() to return to the main screen.

However I'm now wanting to keep the sub activities in memory so that the user can go back, see what they have entered and adjust the search criteria rather than re-entering it from scratch. How do I swap back to my main activity without losing the state of the sub activity?

Thanks,

m

Upvotes: 1

Views: 1219

Answers (2)

blessanm86
blessanm86

Reputation: 31779

Yuo should utilize android intent flags. Use the flag FLAG_ACTIVITY_REORDER_TO_FRONT

If set in an Intent passed to Context.startActivity(), this flag will cause the launched activity to be brought to the front of its task's history stack if it is already running.

For example, consider a task consisting of four activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then B will be brought to the front of the history stack, with this resulting order: A, C, D, B. This flag will be ignored if FLAG_ACTIVITY_CLEAR_TOP is also specified.

An alternative way to pass data between activities would be to extend the Application class. So in each activity you could access it using

MyApplication myApp = (MyApplication) getApplicationContext();

You could set you search criteria to a attribute in this class. You can access the application context from any activity.

Upvotes: 1

inazaruk
inazaruk

Reputation: 74780

From your description it looks like main activity receives data from all sub-activities. It also sounds like this data is enough to restore the state of each subactvity.

You could start sub-actvities with already known search criteria in the Intent. So each sub-actvitiy could restore its state from intent on onCreate().

Here is a sequence of events:

  1. Application starts, Main Activity starts.
  2. User presses button: Main Activity -> Intent (empty) - > Sub-Activity
  3. User completed search criteria:
    Sub-Activity returns -> Intent (search criteria) -> Main Activity
  4. User presses button: Main Activity -> Intent (search criteria) -> Sub-Activity

So on step 4 Main Activity would pass the state received on step 3.

Upvotes: 2

Related Questions