I have on the first Activity list of products that the user can sort and filter. If the user goes to the second Activity , and then with the help of Intent goes back to the first one, then the Activity simply rebuilds all the actions that the user performed on the list (sorting and filtering) are not saved. I read about onSaveInstanceState() , but it is written that it is not called when an activity instance is destroyed by a user action (when the BACK key is pressed). What should I do in this situation?

  • Where is your data stored between app launches? - pavlofff
  • So far, the data is stored in a local database, but in the future the database will be stored on the server. - SviatoIa
  • I think that the sorting and filtering parameters will most reasonably be stored either in the SharedPreferences , as in the last paragraph of the answer below, or in the database itself to make a table for these parameters, if they should be associated with this database (on different devices, the same parameters when opening this database ) - pavlofff

1 answer 1

Perhaps, you can use the option not to close the first activity, but simply open a new one on top of it. When you close the second activity, the previous one will just appear on the screen in the state in which you left it.

To do this, you do not need to call the function finish (); when you go to the second activity, and the second activity simply close function finish (); without using intent. Just in case, in AndroidManifest.xml, you can indicate by the activity parameter that it does not need to be closed:

 <activity .... android:noHistory="false" </activity> 

Although it is not necessary, because this attribute defaults to false.

There is also an option to keep some public static array with settings. It may even be to write the settings in SharedPreferences so that they are saved after the restart. Initially, some default settings are set. OnCreate activity each time takes these settings and creates a list according to them.

  • 2
    The first is very bad advice. Activation not in the foreground can be destroyed at any time and no one guarantees its safety, besides, when returning, the activity is created anew, which means that the past state with 99% probability will be lost. Static with settings can also easily cause memory leaks and here you have to understand well what you are doing - pavlofff
  • I used the first method when there were few activities in the application, but then their number increased and this method was not convenient. It turns out I need to use SharedPreferences ? - SviatoIa