Saving and restoring Activity State when Activity

2019-09-03 04:20发布

问题:

I am working on an App for collecting Customer Details like personal, business, assets etc.

The app shows a ListView with options and based on options Activities are started. After entering details in personal user presses back button and returns to MainActivity (Activity with a ListView) and selects another option like business details and assets detail. User enters the details and come back to MainActivity by Back button and selects another option.

I tried to save my Activitys using onSavedInstance(Bundle) and onRestoreInstanceState(Bundle) and sharedpreference but failed.

Can anyone help? I will provide code if required.

回答1:

OnSaveInstanceState()/OnRestoresInstanceState() is not supposed to be used on a back key pressed from an Activity. In fact , OnSaveInstanceState() is never called. Here the user is explicitly destroying the Activity and removing it from the back stack.

These two methods are used in case where user presses home button or in cases where Android System destroys your Activity.

The options you can try

  1. Try using StartActivityForResult()/OnActivityResult() methods. Here the target activity can set data whcih can be accessed by your parent activity.
  2. Use an application class(a single instance class (singleton class) for holding data).
  3. Things like shared SharedPreferences, files, database, etc.