1

My app has two tabs and switching between the tabs, makes me lose anything I enter in Current Trip So I modified my code to save the state.

enter image description here

package com.test.testing;


public class Trip2 extends Fragment {
     EditText nameOfInf;    
    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {

        if ((savedInstanceState != null) && (savedInstanceState.getString("nameof") != null)) {
            Toast.makeText(getActivity(), savedInstanceState.getString("nameof"),2000).show();
        }
        else {
            Toast.makeText(getActivity(), "DIDNT SAVE",2000).show();
        }
        final RelativeLayout mFrame2 =  (RelativeLayout) inflater.inflate( R.layout.trip, container, false ); 

        final Button btnCalc = (Button) mFrame2.findViewById(R.id.btnCalculate);

        nameOfInf = (EditText) mFrame2.findViewById(R.id.etName);
        final EditText tollAmount = (EditText) mFrame2.findViewById(R.id.etToll);

        btnCalc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //DO SOMETHING
            }
        });
        return mFrame2;
    }
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("nameof", nameOfInf.toString());
}
}

It always displays

DIDN't SAVE

How do I fix the issue?

Si8
  • 9,141
  • 22
  • 109
  • 221
  • did you try [setRetainInstance()](http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)) ? That way you won't need to manage state saving and restoring. – Andrii Chernenko Jul 30 '13 at 20:54
  • Lots of good information here http://stackoverflow.com/q/151777/1316346 – Kevin DiTraglia Jul 30 '13 at 20:54

1 Answers1

3

You don't need setRetainInstance, in fact that would not work at all.

What happens is that pressing a tab calls your TabListener where, most likely, you run a replace transaction, removing the old fragment and discarding its saved data. You should only add if the tab didn't exist before (use fragment tags to determine that) and detach/attach otherwise. Once you do that, you won't even have to save the text manually since View state is automatically saved.

Delyan
  • 8,881
  • 4
  • 37
  • 42
  • I think you are going somewhere with it... I think you are referring to `attach` and `detach`? `onTabUnselected` and `onTabSelected`? – Si8 Jul 30 '13 at 21:02
  • Correct. You want to `detach` tabs that you're unselecting and `attach` tabs that you're selecting, if they already exist. If they don't, you need to `detach` the previous one and `add` the new one. – Delyan Jul 30 '13 at 23:14