Save state of activity - android

I'm trying to save and restore state of activity in my app.
I don't want to save it when it's closed, but when it is paused (going to another activity, etc.) It behaves like that, when I press the home button, but it's default.
when I click on ListView item and get back to my activity I would like my app to:
-show the items again with no need to recreate it again
-show the last position of ListView (int)
I am using an ArrayList of custom objects - ArrayList
Could you please advice me which method is the best to use in my case?

This behavior is built into the activity and fragment lifecycle as instance states:
You can save the instance state using Activity.onSaveInstanceState(Bundle savedInstanceState) where you add items into a Bundle.
Similarly, you can read this instance state in Activity.onCreate(Bundle savedInstanceState) and Activity.onRestoreInstanceState(Bundle savedInstanceState).
I strongly encourage you to read the documentation here.

Related

Do we also have to save previous activity state on resource cleanup in background when using startActivityForResult()?

I have a main activity which takes me to another activity using startActivityForResult() . The resulting activity performs a process and ultimately returns an object back to main activity . My question is:
If user presses home button on his android screen while he was in result activity and android cleans up the resources of my app, Do i have to only save the state of my resulting activity of or i do also have to save states of both the main and resulting activity in order to restore my app current state.
If i have to save the states of both the activities, how do i do that ?
P.s:
I have some data added to my main activity. I would like to restore my state for both result and main activity .
If user presses home button on his android screen while he was in result activity and android cleans up the resources of my app, Do i have to only save the state of my resulting activity of or i do also have to save states of both the main and resulting activity in order to restore my app current state
You do not need to trigger onSaveInstanceState() manually. So everything with a state which is saved by executing this method will be persisted automatically.
BUT
not even the state of all Views will be saved by default. For example a TextView of which you changed the text will revert to the text in the layout file if you do not set the attribute android:freezesText="true"
if you have some data stored in a field (property) of your Activity, it will be lost if you don't take steps to persist it (note this is also valid for ViewModels - they survive a configuration change but they are not immortal).
Options for persisting data: if related to the View layer like e.g. a selected item in a RecyclerView, one can override onSaveInstanceState() and save the item id in the savedInstanceState Bundle. Other possibilities include writing to SharedPreferences and having a SQLite database. See also Options for preserving UI state and Data and file storage overview

How to keep informations in fragment after onBackPressed?

I'm newbie in android and I'm working with fragments.
My problem:
I have two fragments, "A" and "B", my fragment "A" is a complex form, the user can add and remove products, set customer information, payment method and more. My fragment "B" just show the information that user set in the previous fragment.
But if user press back button, I'm losing all information that already set in the previous fragment.
How can i maintain this informations on fragment A?
Thanks.
you can save your data by using sharedpreferences
so that once you get back to the fragment you load your data from sharedpreferences
You should add android:id attribute to each View element of which state you want to save.
this explains in android documentation:
By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.
Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.

Restoring instance variables in Android upon activity recreation

I have an Android project for which I am creating a custom tab view. I have structured the main Activity (FragmentActivity) in such a way that it has a tab bar at the bottom of the screen with a FrameLayout above it. Each option on the tab creates a new Fragment (relating to that option). Now, to prevent recreation of fragments each time an option is clicked, I store the fragment in an instance variable in the activity. So, when a tab option is clicked, I check if its fragment is already created, if it is not already created, I create and add it to the FrameLayout (and hide any existing fragment), otherwise, I just hide the existing fragment (stored in an instance variable called currentlyViewedFragment) and show the already created fragment that matches the clicked option.
Also when the onCreate() of the activity is called, I set the initial tab to be the home tab (one of the tabs).
This works great, except when the activity is recreated (due to orientation changes). Here, I think the instance variables (essentially pointers to already created fragments) loose their value and are set to null. This causes the home tab to be created and be overlayed on the restored view. I also know that you can save state using the bundle passed to onSaveInstanceState and restore it using onRestoreInstanceState. But the bundle needs to contain data which is serialisable. However, these instance variables are merely pointers! How do I restore their values?
NOTE: this problem is solved below in a comment posted by me.
Thanks.
The answer to your problem is using the bundle for state restoration. Create a class in where you can put the variables and is serializable so you can put the its object to the bundle. Or you may also use SharedPreferences to store the instance variables' value in the phone storage. I hope you got idea from my weird answer.

View state at fragment on backstack with retaininstance = true

I have got loader in fragment and it loads data on background. After data are loaded, I fill edittexts with that informations. Problem is that if user changes something in edittexts and rotate screen, onLoadFinished is called again and edittexts are replaced with loaded information. I solve this by adding help variable, if data was already loaded .. But when i replace this fragment with other, rotate screen back and forth and press back button, edittexts are empty. Fragment is set to retain instance true. It looks like views lost its state when fragment is on backstack. Anyone familiar with this?
You shouldn't use the retain state.
But the proper way to do so it to save the save using the Bundle and restore it when you recreate the activity (onCreate Bundle is not new).
Please review the link I've sent you it includes a very specific example.
from the android dev guide:
To properly handle a restart, it is important that your activity
restores its previous state through the normal Activity lifecycle, in
which Android calls onSaveInstanceState() before it destroys your
activity so that you can save data about the application state. You
can then restore the state during onCreate() or
onRestoreInstanceState().
Android Rotation Change

Save activity state(not just some variables) on orientation change

I realized that there are lots of question on this topic already asked on SO.
But I don't even know the basic when it comes to saving the state of an activity.
(Refer Screenshot Below) When app launches,
1) ScrollView item 1,2,3,4 are visible
2) table containd data which is populated due to Gainer button.
As showed in below screenshots, While app is running in PORTRAIT mode, I
1)scrolled down to ScrollView item 4,5,6
2)pressed the Loser button so accordingly data in the table below the button changes.
3)I'll even change content of graph dynamically(which I had not done yet).
Now I switch to LANDSCAPE Mode so
1)ScrollView is showing ScrollView item 1,2,3,4
2)table is showing data which is populated due to pressing Gainer button.
3)graph is as it is as I've not changed it yet(which I will change later).
So what happens is when I change the orientation, my activity is getting re-launched. So if user is performing some task in one orientation and he changes the orientation, then whole progress will be lost.
I know I need to save the state of the activity and Restore it when orientation changes.
But I don't know from where to start and what to save.
ANY HELP WILL BE LIFE-SAVER !
Option #1: Override onSaveInstanceState() of your Activity and put whatever information you want in the supplied Bundle. Your new activity instance will receive that Bundle in onRestoreInstanceState() (or onCreate()). Here is a sample project demonstrating this.
Option #2: Override onRetainNonConfigurationInstance() of your Activity and return some object that represents your state. Your new activity instance can call getLastNonConfigurationInstance() to retrieve that object, so the new activity can apply that information. Be careful, though, not to have the old activity return something in the object that holds a reference back to the old activity (e.g., a widget, an instance of a regular inner class). Here is a sample project demonstrating this.
Option #3: Convert this activity to a fragment. Have the fragment call setRetainInstance(true); on itself during its initial setup. Add the fragment dynamically to some activity via a FragmentTransaction. Now, when the configuration changes, the fragment is retained, so all your widgets and state are retained. Here is an overly-complex sample application demonstrating this.
Those are the three recommended approaches nowadays.

Categories

Resources