Is it save to overrwrite the savedInstanceState bundle after passing it up? - android

I have the following (to avoid checking if a fragment is being created newly or just being recreated)
#Override public void onActivityCreated(Bundle args) {
super.onActivityCreated(args);
if (this.getArguments() != null) args = this.getArguments();
// rest of fragment loading goes here
}

Not sure what you are trying to do never seen budle values being overwritten.
If you want some values to be availbale inside fragment pass those values to activity and inside fragment call getActivity().getIntent().getExtra(
Otherwise have a look at code below if want save some fragment data if fragment is destroyed
Inside fragment in onCreate method check if savedInstanceState is null or not
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
//fragment recreated
}
}
Save data as follows
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (jsonObject != null) {
outState.putString(Constants.JSON, jsonObject.toString());
}
}

Related

Recyclerview in fragment not loading after screen rotate

I want to save my fragment with recycler view, to restore it whlie screen rotate. I was looking for instructions in the net and I get:
In my Fragment
private Parcelable recyclerViewState;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
list.getLayoutManager().onRestoreInstanceState(recyclerViewState);
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
recyclerViewState = layoutManager.onSaveInstanceState();
}
in my Activity
//onCreate
if (savedInstanceState != null) {
getSupportFragmentManager().getFragment(savedInstanceState, LIST_USERS_FRAGMENT);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().getFragment(outState, LIST_USERS_FRAGMENT);
}
I was debbuging and it looks fine, however while I rotate my screen I get blank fragment, with no recycler view. Could You help me investigate why it's happening ?
The default behavior in Android is destroying all the attached fragments on configuration changes. To bypass fragment recreation you should use setRetainInstance(true) in the OnCreate callback of the fragment.
There are a different options to handle the orientation changes:
Lock screen orientation
<activity
android:name="com.example.test.activity.MainActivity"
android:screenOrientation="portrait"/>
Prevent Activity to recreated
<activity
android:name="com.example.test.activity.MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden"/>
Save basic state
public class MainActivity extends Activity{
private static final String SELECTED_ITEM_POSITION = "ItemPosition";
private int mPosition;
#Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
// Save the state of item position
outState.putInt(SELECTED_ITEM_POSITION, mPosition);
}
#Override
protected void onRestoreInstanceState(final Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Read the state of item position
mPosition = savedInstanceState.gettInt(SELECTED_ITEM_POSITION);
}
}
Save complex objects
Override
onRetainNonConfigurationInstance()
getLastNonConfigurationInstance()
After API level 13 these methods have been deprecated in favor of the more Fragment’s setRetainInstance(boolean) capability, which provides a much cleaner and modular means of retaining objects during configuration changes.

How to save fragment state with annotations?

I have a little project, one activity and two fragment. I have started from the "Bottom Navigation Activity" sample on a new projet.
The I use the Android Annotations (https://github.com/androidannotations/androidannotations/wiki) for injecting my fragment, It display correctly but when I rotate, I loose all my information and the app display the first fragment, even if I displayed the second one. I tried to save my data, from an edit text with a Bundle object, in the "onSaveInstanceState" method, I get back it in the "onActivityCreated" or in the "onCreate" method but after their method were re-call and my data desappear.
I don't know how to save which fragment was displayed and how re-displayed it with the android annotations.
In my Activity class I have those methods :
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
And in my main fragments :
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(dpdEditText != null){
rttNumberTemp = rttEditText.getText().toString();
outState.putString("rttNumberTemp", rttNumberTemp);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(Tag, "onActivityCreated");
if(savedInstanceState != null){
Log.d(Tag, "onActivityCreated if");
updateEditText(rttEditText,savedInstanceState.getString("rttNumberTemp"));
}
}
So my question is how can I save my fragment, and its data and which fragment is displayed ?
I finally find my mistake. In my main activity I have the following method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
So the program call the view by the injection and call it again with the setContentView. So I update the method like that :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

savedInstanceState is always null value in onCreate

This is my onCreate method in a class which is subclass of fragment
static int counter = 0;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState == null) { //made for first time
Log.d("came in", "Came in");
counter = 0;
} else {
counter = savedInstanceState.getInt("counter", 0);
}
}
this is my savedInstanceState method
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
Log.d("hi there", ""+counter); // this is printing hi there 3
outState.putInt("counter", counter);//key value pair
}
but in onCreate method savedInstanceState is always null and printing came in.
Override protected void onRestoreInstanceState(Bundle savedInstanceState) and see if you can get your values there.
Try to save your value in your fragment host activity(Activity in which your fragment is defined). From host activity, you have to extract that value and access it in your fragment subclass.
try change you method onSaveInstanceState to:
#Override
public void onSaveInstanceState(Bundle outState){
Log.d("hi there", ""+counter); // this is printing hi there 3
outState.putInt("counter", counter);//key value pair
super.onSaveInstanceState(outState); // call super after put int
}

Orientation: restore ListView position that is inside a Fragment

I went trough a famous post in SO, Maintain/Save restore scroll position
but does not help me at all.
I have a ListView inside a Fragment, if I change the orientation, I would like that saveInstance Bundle will save my position.
I have
private static final String LIST_STATE = "listState";
private Parcelable mListState = null;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mListState = listView.onSaveInstanceState();
outState.putParcelable(LIST_STATE, mListState);
}
and does not matter if I put in OnCreateView or in onActivityCreated the following code
if(savedInstanceState!=null) {
mListState = savedInstanceState.getParcelable(LIST_STATE);
listView.onRestoreInstanceState(mListState);
the up position of the list is not restored at all.
I can easily see from the debug in Bundle that the debug recognize in the Bundle the position,
AbsListView.SavedState{3d7562e0 selectedId=-9223372036854775808
firstId=25 viewTop=-38 position=5 height=717 filter=null
checkState=null}
I even tried to extract from the Bundle this position in an isolated way instead of all the values, but without success.
add following code inside fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
Found it!
The solution is
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mPosition2=listView.getFirstVisiblePosition();
if(mPosition2!=0) {
mPosition = mPosition2;
}
if (mPosition != ListView.INVALID_POSITION) {
outState.putInt(SELECTED_KEY, mPosition);
}
}
and in onCreateView
if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
mPosition = savedInstanceState.getInt(SELECTED_KEY);
}
finally I have a loader that query a content provider at end of onLoadFinished( but you can put you just where you need)
if (mPosition != ListView.INVALID_POSITION) {
listView.setSelection(mPosition);
I have also tried listView.smoothScrollToPosition(mPosition)
but is not working at the moment, but never mind it works really well to me.

Saving the state of my App through rotation

I am building a memory game app for a java class and i need to save which words are displayed through rotation of the device...the widgets that need to be saved and passed to the new onCreate() method are button widgets that i used setText to display the words that are being shown....can i save and pass the entire state of the application...here is my code that is obviously not working and i was hoping i could get some insight...thanks...here is my code..
private Bundle myBundle = new Bundle();
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eight);
if(savedInstanceState != null) {
savedInstanceState = myBundle;
}
......
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
myBundle = savedInstanceState;
}
You got the semantics of using the Bundle backwards. You don't ever want to save the Bundle (or overwrite it). Just use it to serialize your own state variables into it and out of it. For example, if you want to preserve two integer variables and a string between a rotation (such that you can re-initialize the view with these members later), you could do the following:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eight);
if(savedInstanceState != null) {
// Restore our member variables that represent activity state right here from the passed in Bundle.
_x = savedInstanceState.getInt("MyApp.X", 0);
_y = savedInstanceState.getInt("MyApp.Y", 0);
_name = savedInstanceState.getString("MyApp.NAME", "player");
// not shown - initializing the view elements with the initialized member variables.
}
......
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// save our activity state by adding our member variables that represent activity state into the Bundle.
savedInstanceState.putInt("MyApp.X", _x);
savedInstanceState.putInt("MyApp.Y", _y);
savedInstanceState.putString("MyApp.NAME", _name);
// call the parent method *after* you have saved your state
super.onSaveInstanceState(savedInstanceState);
}
Bundle also supports arrays of simple types.
In method onSaveInstanceState add values which you want to save like below
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("key","your string here");
}
and inside oncreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null ) {
System.out.println(savedInstanceState .getString("key"));
}
}

Categories

Resources