Saving and restoring state using fragments - android

I'm trying to understand the process of saving and restoring state using fragments. I've created sliding navigation menu using it.
In one of the fragments there is this code:
public class FifthFragment extends Fragment {
CheckBox cb;
View view;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fifth_layout, container, false);
cb = (CheckBox) view.findViewById(R.id.checkBox);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore save state
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save state
}
}
For example I want to save the state of the CheckBox before user exits the fragment and restore it when the fragment is created again. How to achieve this?
EDIT:
According to raxellson's answer I've changed my fragment to this:
public class FifthFragment extends Fragment {
private static final String CHECK_BOX_STATE = "string";
CheckBox cb;
View view;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fifth_layout, container, false);
cb = (CheckBox) view.findViewById(R.id.checkBox);
if (savedInstanceState == null) {
Log.i("statenull", "null");
}
if (savedInstanceState != null) {
// Restore last state for checked position.
boolean checked = savedInstanceState.getBoolean(CHECK_BOX_STATE, false);
cb.setChecked(checked);
}
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(CHECK_BOX_STATE, cb.isChecked());
}
}
I got logged I/statenull: null so savedInstanceState was not saved. What am I doing wrong?

You want to save the value of your current checked state in onSaveInstanceState.
Something like this:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(CHECK_BOX_STATE, cb.getChecked());
}
and then when your view is created you want to get the value if it's present. And set your CheckBox state with it.
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fifth_layout, container, false);
cb = (CheckBox) view.findViewById(R.id.checkBox);
if (savedInstanceState != null) {
// Restore last state for checked position.
boolean checked = savedInstanceState.getBoolean(CHECK_BOX_STATE, false);
cb.setChecked(checked);
}
return view;
}
EDIT:
When you add the fragment, make sure to add it with a tag or id so that you can retrieve the same instance.
You could do a helper method to retrieve fragment and set the fragment.
private void setFragment(String tag, Fragment newFragment) {
FragmentManager fm = getSupportFragmentManager();
Fragment savedFragment = fm.getFragmentByTag(tag);
fm.replace(R.id.container, savedFragment != null ? savedFragment : newFragment, tag);
fm.commit();
}
so you your switch you can call the helper method instead.
switch (position) {
case 0:
setFragment("A", new FragmentA());
break;
....
}
Note: This is just an example not best practice since you are creating new fragments every time in your switch case now anyways. But it might point you in the right direction.

After see all the example. Here is the solution for save fragment state:
Two steps for this:
1.
String saveValue;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
saveValue = "";
} else {
saveValue = savedInstanceState.getString("saveInstance");
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//save the values of fragment if destroy on second to back
if (!saveValue.isEmpty())
savedInstanceState.putString("saveInstance", saveValue);
}
In onSaveInstanceState you can save your values. And after destroy fragment you can receive your values through onCreate.

Related

Fragment's state is not being retained

I am calling fragment's onSaveInstance() method in which I have saved the value of edittext and checbox in bundle. In onCreateView I am setting those values to my edittext and checkbox but when I run the app and write something in edittext and rotate my device it becomes blank! can anyone help?
public class BlankFragment extends Fragment {
public EditText ed;
public CheckBox cb;
public BlankFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_blank, container, false);
ed = v.findViewById(R.id.edit);
cb = v.findViewById(R.id.check);
if(savedInstanceState != null){
ed.setText(savedInstanceState.getString("string"));
cb.setChecked(savedInstanceState.getBoolean("bool"));
}
return v;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString("string",ed.getText().toString());
outState.putBoolean("bool",cb.isChecked());
super.onSaveInstanceState(outState);
}
}
I have logged those setText and setChecked lines, it prints correct values in log but then why it is not setting anything on views!

Fragment - wait for onCreateView() to complete before running methods

I'm struggling with a puzzling sequence of events relating to a Fragment. I'm trying to add a fragment to an Activity, and then call a method inside the fragment to update some text. However, what I am finding is that the method is being processed in the fragment before onCreateView() finishes, which leaves me with a null View object, and my method fails. Here is the Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_entry_details);
fragmentManager = getSupportFragmentManager();
titleBarFragment = new TitleBarVerticalFragment();
fragmentTransaction = fragmentManager.beginTransaction ();
fragmentTransaction.add(R.id.log_entry_title_frame, titleBarFragment);
fragmentTransaction.commit();
titleBarFragment.updateTitleBar("Edit Log Entry", 20, false);
}
Seems simple enough. Here is the TitleBarVerticalFragment class:
public class TitleBarVerticalFragment extends TitleBarFragment {
#Inject SharedVisualElements sharedVisualElements;
View view;
TextView titleLabel;
public TitleBarVerticalFragment() {
// add this line for any class that want to use any of the singleton objects
Injector.INSTANCE.getAppComponent().inject(this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Log.d(Constants.TAG, "title fragment onCreateView()");
view = inflater.inflate(R.layout.fragment_title_bar_vertical, container, false);
ImageView logoImage = (ImageView) view.findViewById(R.id.logo_vertical);
titleLabel = (TextView) view.findViewById(R.id.verticalTitleLabel);
titleLabel.setTextColor(sharedVisualElements.secondaryFontColor());
titleLabel.setTypeface(sharedVisualElements.font());
titleLabel.setTextSize(20);
logoImage.setImageDrawable(sharedVisualElements.logoImage());
logoImage.setBackgroundColor(Color.TRANSPARENT);
return view;
}
public void updateTitleBar(String text, int textSize, boolean titleLabelIsHidden) {
Log.d(Constants.TAG, "about to update title bar text");
if (view == null) {
Log.d(Constants.TAG, "vertical title fragment is null");
return;
}
if (titleLabel == null)
titleLabel = (TextView) view.findViewById(R.id.verticalTitleLabel);
if (titleLabel == null) {
Log.d(Constants.TAG, "vertical title label is null");
return;
}
Log.d(Constants.TAG, "updating title text: " + text);
titleLabel.setText(text);
titleLabel.setTextSize(textSize);
}
Note the order of this logcat output. Notice how onCreateView() seems to run after the updateTitleBar() method? How can that be?
about to update title bar text vertical title fragment is null
title fragment onCreateView()
How can I ensure that onCreateView() runs before I call any of the fragment's other methods? Thank you.
Try running fragmentManager.executePendingTransactions() after fragmentTransaction.commit(); and before titleBarFragment.updateTitleBar("Edit Log Entry", 20, false);
Just use onStart() on your activity
Define a listener interface and implement it in your Activity.
interface LyfecycleListener {
void onCreatedView();
}
in your Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
this.titleBarFragment = new TitleBarVerticalFragment();
this.titleBarFragment.setListener(this)
...
}
#Override
public void onCreatedView() {
titleBarFragment.updateTitleBar("Edit Log Entry", 20, false);
}
in your Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
this.listener.onCreatedView();
}

Listview fragment is getting recreated on pressing backbutton

I'm using loader in my ListView fragment, and it's getting recreated on pressing "back" button. Can you tell me how to handle this senario?
Here is my ListView fragment code. Here I have a boolean variable that I'm setting as true on clicking on list item. but once the back button is pressed onCreateView will get called so the backbutton will be false.
public class GTFragment extends SherlockFragment implements LoaderCallbacks<Cursor>{
ListView mTListview = null;
GoogleTasksAdapter mGTasksAdapter = null;
private SQLiteCursorLoader mTLoader=null;
private LoaderManager mTLoaderManager;
private String mSelectedListID = null;
private boolean mIsBackbuttonisPressed = false;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_home_activity, container, false);
if(!mIsBackbuttonisPressed)
getLoaderManager().initLoader(0, null, this);
mTListview = (ListView) view.findViewById(R.id.id_task_list_home_activity);
mGTasksAdapter = new GoogleTasksAdapter(getActivity());
mTListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview,
View clickedview, int position, long arg3) {
// TODO Auto-generated method stub
GoogleTaskItem item = new GoogleTaskItem();
Cursor coursor = ((GoogleTasksAdapter)listview.getAdapter()).getCursor();
if(coursor.moveToPosition(position))
{
mIsBackbuttonisPressed = true;
GoogleTaskController.get_googletask_controllerObj()
.LaunchTaskPreviewActivity();
}
}
});
mTListview.setAdapter(mGTasksAdapter);
mIsBackbuttonisPressed = false;
return view;
}
My fragment activity class code
public class TLActivity extends SherlockFragmentActivity {
LeftSliderTaskListOptions mTaskOptionsFragment = null;
GoogleTasksFragment mTFragment = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.layout_gt_list);
// FragmentTransaction tfragment = this.getSupportFragmentManager().beginTransaction();
mTFragment = new GTasksFragment();
t.replace(R.id.id_tfragment, mTFragment);
t.commit();
}
instead of
t.replace(R.id.id_tfragment, mTFragment);
use
t.add(R.id.id_tfragment, mTFragment);
It worked for me
I don't think that the accepted answer is right because Fragment.onSaveInstanceState will not be called until the activity hosting it needs to save its state: The docs states:
There are many situations where a fragment may be mostly torn down
(such as when placed on the back stack with no UI showing), but its
state will not be saved until its owning activity actually needs to
save its state.
In other words: if you're using a Activity with multiple fragments for each screen (which is very common), the fragment state will not be saved when you move the next screen.
You also can't use Fragment.setRetainInstance because he's meant only to fragments that aren't on the back stack.
Most of the time, you don't have to think about this but sometimes it's important. Like when you have scrolled a list and want to "remember" the scroll location.
I took a long time to realize that the fragments put on the back stack are kind of saved and you can reuse the view that you already created instead of creating one every time the fragment calls onCreateView. My setup is something like this:
public abstract class BaseFragment extends Fragment {
private boolean mSaveView = false;
private SoftReference<View> mViewReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mSaveView) {
if (mViewReference != null) {
final View savedView = mViewReference.get();
if (savedView != null) {
if (savedView.getParent() != null) {
((ViewGroup) savedView.getParent()).removeView(savedView);
return savedView;
}
}
}
}
final View view = inflater.inflate(getFragmentResource(), container, false);
mViewReference = new SoftReference<View>(view);
return view;
}
protected void setSaveView(boolean value) {
mSaveView = value;
}
}
public class MyFragment extends BaseFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setSaveView(true);
final View view = super.onCreateView(inflater, container, savedInstanceState);
ListView placesList = (ListView) view.findViewById(R.id.places_list);
if (placesList.getAdapter() == null) { // this check is important so you don't restart your adapter
placesList.setAdapter(createAdapter());
}
}
}
You have multiple options to rectify this issue.
Override onSaveInstanceState like this:
#Override
public void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("mIsBackbuttonisPressed", mIsBackbuttonisPressed);
}
and then in your onCreateView you can get your variable back by:
if (savedInstanceState != null)
mIsBackbuttonisPressed = savedInstanceState.getBoolean("mIsBackbuttonisPressed", false);
You can set this.setRetainInstance(true); in your onCreate method of your fragment.
If you could post your Activity code with creates your fragment I can also tell you other options. (P.S I cannot write it as a comment so posting it in the answer.)

Keep list fragment selected item position on orientation change

I have a list fragment on the left of another fragment and is essentially the standard click an item and update the right fragment pattern. When they click an item in the list fragment they are choosing the news article category and I need to keep whatever one is selected when they rotate the device. How do I do that? My current code doesn't work.
My code is as follows:
public class SideMenuFragment extends ListFragment {
ArrayList<SideItem> sideItems;
SideAdapter sideAdapter;
public SideMenuFragment() {
this.setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
sideItems = new ArrayList<SideItem>();
...add bunch of items
sideAdapter = new SideAdapter(getActivity(), sideItems);
getListView().setVerticalScrollBarEnabled(false);
setListAdapter(sideAdapter);
if (savedInstanceState != null) {
sideAdapter.setSelectedItem(savedInstanceState.getInt("sidePosition"));
sideAdapter.notifyDataSetChanged();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("sidePosition", sideAdapter.getSelectedItem());
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
if (sideAdapter.getSelectedItem() != position) {
sideAdapter.setSelectedItem(position);
sideAdapter.notifyDataSetChanged();
}
switch (position) {
...switch the fragment depending on position.
}
}
// the meat of switching the above fragment
private void switchFragment(Fragment fragment, String title) {
if (getActivity() == null)
return;
if (getActivity() instanceof HomeActivity) {
HomeActivity a = (HomeActivity) getActivity();
a.switchContent(fragment, title);
}
}
}
First, add your Fragment in xml if the Activity layout.
In Activity onCreate
getFragmentManager().findFragmentById(R.id.youtfragmentid).setRetainInstance(true)
This means that the fragment will not be recreated on activity recreate.
Don't change your ListView in onActivityCreated - because it will be rebuilt every time orientation changes. If you set a new adapter - the states of children will be reseted.
Add checking for null or a boolean flag that the view already was created.
Next time onActivityCreated gets called, your list adapter should not change
if (sideAdapter == null) {
sideAdapter = new SideAdapter(getActivity(), sideItems);
getListView().setVerticalScrollBarEnabled(false);
setListAdapter(sideAdapter);
}
Also, don't create new view in onCreateView instead use previously created one.
private View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (v == null) {
v = inflater.inflate(R.layout.list, null);
} else {
// detatch from container and return the same view
((ViewGroup) getListView().getParent()).removeAllViews();
}
return v;
}

Fragment doesn't call onSaveInstanceState when swiping ViewPager?

I'm having an issue with the ViewPager where my ListView is loosing it's scroll position.
The state of the ListView can easily be stored and restored using:
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.frag_cool_things, container, false);
AdvListView listView = (AdvListView) v.findViewById(R.id.lv0);
listView.setOnItemClickListener( mOnListItemClicked );
if (null != savedInstanceState)
{
listView.onRestoreListViewInstanceState(savedInstanceState.getParcelable("list_state"));
}
mListView = listView;
return v;
}
#Override
public void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putParcelable("list_state", mListView.onSaveListViewInstanceState());
}
However the problem is that when fragments are being swiped onDestroyView() gets called but never calls onSaveInstanceState (Bundle outState).
Rotating the screen and such restores the ListView state just fine but swiping I can't figure out how to restore the list properly.
Update 12/17/11:
I actually found the correct way to save the content of the Fragments. You must use FragmentStatePagerAdapter. This adapter properly saves the state of the fragment! :)
OLD:
Well I found a way to do this.. Please share your input if you believe this is a huge no no! :P
Here is my FragmentBase class that fixed this issue:
public abstract class FragmentBase extends Fragment
{
private boolean mInstanceAlreadySaved;
private Bundle mSavedOutState;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
if (null == savedInstanceState && null != mSavedOutState) {
savedInstanceState = mSavedOutState;
}
mInstanceAlreadySaved = false;
return onCreateViewSafe(inflater, container, savedInstanceState);
}
#Override
public void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
mInstanceAlreadySaved = true;
}
#Override
public void onStop()
{
if (!mInstanceAlreadySaved)
{
mSavedOutState = new Bundle();
onSaveInstanceState( mSavedOutState );
}
super.onStop();
}
public abstract View onCreateViewSafe (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
}

Categories

Resources