How to keep informations in fragment after onBackPressed? - android

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.

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

Can onSaveInstanceState(...) be used when switching between activities?

I do have 2 activities A (contains a button that redirects to A and a text input) and B (contains a button the redirects to A) and I was trying to switch from one to another but also to keep the text value from A.
I was trying to save the text value in a Bundle using onSaveInstanceState(...) but it simply didn't work.
Here are the steps I do:
(on A) add some text
in A, implement onSaveInstanceState(...) and save the value of text in Bundle
(on B) click the button that points back to A
(on A) the stored value is gone (also the Bundle sent to onCreate(...) is null)
To my surprise when I'm in A and change the orientation the value is stored (and the Bundle sent to onCreate(...) is not null)
Did I miss something?
In short, no.
onSaveInstanceState is meant to save the instance state during things like:
Memory pressure
Screen rotation
Whenever the system decides to stop the activity and resume it later (e.g. it moves to the background, get's forgotten by the user, and later is being picked up again).
Further reading is available here.
You should store those values you want to keep in SharedPreferences, for example during your onPause call.
No you can not use onSaveInstanceState() while switching between activities.
onSaveInstanceState() Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).
This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).
You can get more idea on Android Developer pages:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

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.

Save state of activity

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.

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

Categories

Resources