onSaveInstanceState in Fragment not working? - android

I need help.I don't know what is wron here.Need Saved Instance Data in fragment but it's not working for me? Can anyone help ? Here is my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
if (savedInstanceState == null) {
Log.e(getActivity().getClass().getSimpleName(),"DATA is NULL");
}else{
Log.e(getActivity().getClass().getSimpleName(),"DATA IS NOT NULL " + savedInstanceState.getString(Constans.SAMPLEDATA));
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(Constans.MOVIE, movie);
outState.putString(Constans.SAMPLEDATA, "sampleData");
}

This is happening because on screen rotate your activity gets recreated so does the fragment inside it start from initial position again as it was started on activity first launch
You need to add this in onCreate of your activity and set the fragment inside if statement like this example
if (savedInstanceState == null){
launchfragment
} else {
// do nothing
}
hope this helps

Add super.onSaveInstanceState(outState);
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(Constans.MOVIE, movie);
outState.putString(Constans.SAMPLEDATA, "sampleData");
super.onSaveInstanceState(outState);
}

Related

TableLayout not showing when restored from savedInstanceState

I have a tableLayout in a fragment that´s not showing anything when the information used to populate the cells is taken from the savedInstanceState bundle from OnCreateVIew()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = initializeViews(inflater,container);
if (savedInstanceState!= null){
cellsTextArrayList = savedInstanceState.getStringArrayList("extractedTextEt");
for (String word: cellsTextArrayList){
addRow(word);
}
}
return rootView;
}
private void addRow(String word){
final TableRow tr = new TableRow(getActivity().getApplicationContext());
final View view = LayoutInflater.from(getActivity().getApplicationContext()).inflate(R.layout.cell_layout, null);
EditText actualCell = view.findViewById(R.id.cell_text);
actualCell.setText(word);
tr.addView(view);
tableLayout.addView(tr);
}
#Override
public void onSaveInstanceState (Bundle outState)
{
cellsTextArrayList.add("first");
cellsTextArrayList.add("second");
cellsTextArrayList.add("third");
outState.putStringArrayList("extractedTextEt", cellsTextArrayList);
super.onSaveInstanceState(outState);
}
The cellsTextArrayList is being restored from the savedInstanceState object, the addRow() method is the one that´s not working. I ran the code on an Activity and it worked so I think this has to do with the Fragment lifecycle.
using onActivityCreated in fragment.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
if (savedInstanceState != null) {
//Restore the fragment's state here
}
}
and then in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate().
class MyActivity extends Activity {
private MyFragment
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
//Restore the fragment's instance
mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
...
}
...
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
}
}

saving using onSaveInstanceState in Fragment

There is a Fragment in my android project in which it gets data dynamically from another class.I save that data(one string and Int) into bundle and And I want that bundle to be restored when screen rotates. So I have used onSaveInstanceState method.
In this fragment, "respond" method get data(one string and Int) from another class. I can print those strings in Logcat in respond method.
Fragment Code:
public class Images extends android.support.v4.app.Fragment implements Imageinfo {
private RecyclerView IRecyclerView;
private RecyclerView.Adapter IAdapter;
private RecyclerView.LayoutManager ILayoutManager;
private Context ctx;
private Bundle bundle=new Bundle();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.images, container, false);
Log.d("ONCREATE VIEW", "TRUE");
IRecyclerView = (RecyclerView) v.findViewById(R.id.images_tab);
IRecyclerView.setHasFixedSize(true);
ILayoutManager = new LinearLayoutManager(getContext());
IRecyclerView.setLayoutManager(ILayoutManager);
if(savedInstanceState!=null){
Log.d("BUNDLE ADDED NOT NULL", String.valueOf(savedInstanceState.size()));
IAdapter = new ImageAdapter(this.getContext(),((fileselect)getContext()).imageset,bundle);
IRecyclerView.setAdapter(IAdapter);
}
else{
Log.d("BUNDLE ADDED NULL", "TRUE");
IAdapter = new ImageAdapter(this.getContext(),((fileselect)getContext()).imageset,null);
IRecyclerView.setAdapter(IAdapter);
}
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState=bundle;
Log.d("SAVING TIME", String.valueOf(outState.size()));
super.onSaveInstanceState(outState);
}
#Override
public void respond(String str,int type) {
if(str!=null) {
if (type == 1) {
bundle.putString(str, str);
Log.d("BUNDLE ADDED", bundle.getString(str));
Log.d("BUNDLE ADDED Size",String.valueOf(bundle.size()));
} else {
bundle.remove(str);
Log.d("BUNDLE REMOVED Size", String.valueOf(bundle.size()));
}
}
}
}
PROBLEM:
Although the method respond receiving data(one string and Int) and saving into Bundle, bundle is becoming size zero in onSaveInstanceState when screen rotated. onSaveInstanceState is getting called whenever i rotate screen but the bundle is becoming size zero. As bundle is becoming size zero, I could not restore the two strings.
OK the problem is that, instead of adding content to the outstate variable, you are trying to reference a local variable.
The point is that the instance of the Images class is destroyed on rotation, and so will your bundle variable.
The correct way to achieve what you are trying to do is to add your strings to the outstate variable in the onSaveInstanceState method, and read it from the savedInstanceState in the onCreateView.
Try this out:
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("YOUR_STRING_NAME", bundle.getString("YOUR_STRING_NAME"));
Log.d("SAVING TIME", String.valueOf(outState.size()));
super.onSaveInstanceState(outState);
}

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.

Why is FragmentPagerAdapter saveState always null?

I want to save the state of my FragmentPagerAdapter so I can reuse it after the orientation of the screen changed. Unfortunately the method saveState returns always null.
My Adapter consists of an ActionBar with two Fragments.
Here ist my method call
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(FRAGMENT, viewPager.getCurrentItem() + 1);
outState.putParcelable(ADAPTER, fragmentTabAdapter.saveState());
super.onSaveInstanceState(outState);
}
But the Adapter in outState is always null. I don't understand why. Is there something special I missed about the use of saveState?
Hope you can help me!
this example works if the fragment is not destroyed
private int pageID;
#Override
public void onPause() {
super.onPause();
pageID = mViewPager.getCurrentItem(); // 1 save
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mViewPager.setCurrentItem(pageID, false); // 2 load
}

Android fragment state always null in onCreateView method and onActivityCreated method

I have used multiple tabs in fragment class. I was failed in saving the state of fragment. I used the method onSaveInstanceState() and save a parameter in it. But when I came back to this fragment the saved state always shows "null". I tried all the questions and answers regarding to this.Still I am facing the same problem. Please could anyone help me to solve this.
MY CODE
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
super.onCreate(savedInstanceState);
Log.d("savedInstanceStateInfo1", "" + savedInstanceState);
if (null != savedInstanceState) {
nAndroids = savedInstanceState.getInt("nAndroids");
Log.d("NANDROIDS", "" + nAndroids);
}
}
// Log.d("State in oncreate : ",""+savedInstanceState);
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
Log.d("SavedinstanestateInfo", "" + savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
// final ActionBar ab=getActivity().getSupportActionBar();
View v = (LinearLayout) inflater.inflate(R.layout.infotab, container, false);
Log.d("SavedinstanestateInfo", "" + savedInstanceState);
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("nAndroids", nAndroids);
super.onSaveInstanceState(outState);
}
1) Apparently when using setRetainInstance(true), the Bundle for onRestoreInstanceState is null.
https://stackoverflow.com/a/8488107/1011746
2) Not necessary, but more customary to call super.onSaveInstanceState(outState) before making any modifications to outState. Same for super.onRestoreInstanceState(outState) in onRestoreInstanceState(Bundle outState).

Categories

Resources