I have an activity with fragment. Fragment adds to activity like this, depending on some data:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
switch (someId) {
case 1:
mFragment = new Fragment1();
break;
case 2:
mFragment = new Fragment2();
break;
}
}
if (savedInstanceState != null) {
Log.e("onSaveInstanceState Activity", "not null");
mFragment = getFragmentManager().getFragment(savedInstanceState, "mFragment");
}
Bundle args = new Bundle();
args.putString(SOME_TEXT, "example text");
mFragment.setArguments(args);
if (savedInstanceState == null) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_frame, mFragment);
fragmentTransaction.commit();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e("onSaveInstanceState Activity", "onSave");
getFragmentManager().putFragment(outState, "mFragment", mFragment);
}
And then in fragments (assume they are identical):
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Activity activity = getActivity();
setRetainInstance(true);
Bundle in = getArguments();
String field1Text = in.getString(SOME_TEXT);
field1 = (EditText) activity.findViewById(R.id.field1);
if (savedInstanceState != null) {
Log.e("savedInstanceState", "not null");
field1.setText(savedInstanceState.getString("field1"));
} else {
Log.e("savedInstanceState", "null");
field1.setText(field1Text);
}
@Override
public void onSaveInstanceState(Bundle outState) {
Log.e("onSaveInstanceState", "onSave");
outState.putString("field1", field1.getText().toString());
super.onSaveInstanceState(outState);
}
So I thought that fragment would restore its state and setText to EditText field.
But for example when I instantiate fragment with bundle's SOME_TEXT = "example text"
, then change it to "some changes"
in EditText's field, then I move to other app (causing my app to close when memory is low for example):
onSaveInstanceState onSave
is called but onSaveInstanceState Activity
is not.
and when I open it again text in EditText is "example text"
and in logs I have:
savedInstanceState not null
savedInstanceState null
(It seems that onActivityCreated
is fired twice in my case)
but onSaveInstanceState Activity not null
is not called.
so why that text is not as same as I want.
How should I do to restore EditText's field?