I am experimenting with using fragments in my application. I am trying to find a way to store data used by a fragment when I switch my application to the other fragment. My code for my second fragment is found below. When switching to and from this fragment I am using add and remove fragment. This is because when I was using replace, I was having trouble. Whenever I switch to my other fragment, and back to this one, count is not stored. How do I actually store count so I can come back to it when my fragment opens back up?
public class BasicFragment2 extends Fragment {
public int count = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState != null){
count = savedInstanceState.getInt("Integer");
}
View view = inflater.inflate(R.layout.fragment_basic_2, container, false);
Button button = (Button) view.findViewById(R.id.button2);
// A simple OnClickListener for our button. You can see here how a Fragment can encapsulate
// logic and views to build out re-usable Activity components.
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Activity activity = getActivity();
count++;
if (activity != null) {
Toast.makeText(activity, "This is not a fragment...Yes it is " + count, Toast.LENGTH_LONG).show();
}
}
});
return view;
}
public void onSaveInstanceState(Bundle outState){
outState.putInt("Integer",count);
super.onSaveInstanceState(outState);
}
}
Try overriding
onSaveInstanceStatein yourActivityclass and save the count value there. Because as per google docs: