0

So one of my android Fragments, the detail fragment in a master-detail setup, has several possible layouts, depending on what the user wants to do, and one of those layouts contains about a dozen EditText fields for the user to input data.

If the user inputs data, then switches to another layout or another Fragment (from the Detail to the master Fragment), I want to save what they have input so far before performing the switch, without requiring the user to do anything. So I need to know when a particular layout ID was previously inflated and then gets deflated/destroyed/overwritten/etc.

How do I do this? onCreateView(), where I am inflating the new layouts, seems insufficient because it doesn't seem to offer a way to access what was there previously, and AFAIK wouldn't be called if the user switches to the master Fragment anyway. getActivity().getCurrentFocus() at the start of onCreateView() returns a View, but getID() doesn't seem to match when compared to R.layout.my_layout, and calling getActivity().getCurrentFocus().findViewByID() != null on an element in the layout doesn't work either.

Also, when do I perform the saving?

EDIT: Should I override onDestroyView() and run the save code there? Whenever I try to do so, the app crashes.

GarrickW
  • 2,181
  • 5
  • 31
  • 38

1 Answers1

0

Saving and restoring your temporary data based on the Fragments layout IDs would be pretty much anti-pattern I guess.

Instead, add your input data as name-value pairs to the "instance state" Bundle, overwriting onSaveInstanceState(Bundle savedInstanceState) of your Fragment:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  savedInstanceState.putBoolean("myCheckboxState", myCheckBox.isChecked());
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("myInt", 1);
  savedInstanceState.putString("myTextViewString", myTextView.getText());
  // etc.
}

(adapted from this answer)

This Bundle should is accessible in various lifecycle methods after your Fragment has been added to the container again. For example, by overwriting the onActivityCreated(Bundle savedInstanceState) method, you may access this Bundle and pre-fill your form inputs using the respective setter methods.

Depending on your persistence requirements, you could also store your data more globally and not just in the Fragments instance state.

Community
  • 1
  • 1
saschoar
  • 8,150
  • 5
  • 43
  • 46