You will want to override the onSaveInstanceState
method of your activity so that you know when the state needs to be saved. Then you will also need to update your onCreate
method to check if the savedInstanceState
is null
. If it is null
then the activity hasn't been initiated. This is the example for your MainActivity
class, and you can go from there:
MainActivity.java
public class MainActivity extends Activity implements AddToDoFragment.OnToDoAddedListener {
private ArrayList<String> todoItems;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
todoItems = new ArrayList<String>();
} else {
todoItems = savedInstanceState.getStringArrayList("todoItemTag");//the tag must match what the variable was saved with
}
FragmentManager fm = getFragmentManager();
ToDoListFragment listToDo = new ToDoListFragment();
listToDo = (ToDoListFragment) fm.findFragmentById(R.id.list_view_fragment);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems);
listToDo.setListAdapter(adapter);
}
public void OnToDoAdded(String newToDo) {
todoItems.add(newToDo);
adapter.notifyDataSetChanged();
}
//Saving the instance by overriding this function
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("todoItemTag", todoItems);//it would be advised to make the tags a static final String
}
Hopefully this helps!
PS: I don't think the onRestoreInstanceState
method is really necessary. I guess I have never used it before. I believe that you should be able to provide the same functionality with the null
check in the onCreate
method.