I have an Android app with a listview that updates the listview when the user presses a button. The app has two actionbar tabs. When I switch between the tabs, rotate the screen, or press back to exit out of the activity, all the data in the listview disappears. I need the data to remain. I know that at least with the orientation change I can save the data in onSaveInstanceState(). So I save a String[] in savedInstanceState, and retrieve the String[] in onCreateView(). This seems to work fine, it reads the data properly. Then I attempt to update the listview. This also seems to read the data and work properly, only the listview does not update and instead remains blank. My code for this is:
if (savedInstanceState != null) {
lvArray = savedInstanceState.getStringArray("lvArray");
setupListView();
} else {
lvArray= new String[LISTVIEW_LIMIT];
for (int i = 0; i < LISTVIEW_LIMIT; i++) {
lvArray[i] = " ";
}
setupListView();
}
private void setupListView() {
if (listview.getAdapter() == null) {
ArrayAdapter<String> listviewAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, lvArray);
listview.setAdapter(listviewAdapter);
}
registerForContextMenu(listview);
}
So as I said, I go through this, it reads the data properly, it sets up an ArrayAdapter of the data, and sets the adapter for the the listview. It all seems to work, only it doesn't actually update it. I know all the data's there but it's still not working?
Also, I have the ability to set the listview to different sizes (by LISTVIEW_LIMIT). This works fine, except it also removes all the data already in the listview. How can I keep the data instead of recreating the array when the limit changes?
And what would be the best way to save this in onPause() or onStop(), so that I could keep the listview up even if back is pressed or the tab is switched?
EDIT: Changed to use notifyDataSetChanged(), still not working:
lvStopwatch = (ListView) view.findViewById(R.id.list_stopwatch);
stopwatchTimes = new String[TOTAL_TIMES];
for (int i = 0; i < TOTAL_TIMES; i++) {
stopwatchTimes[i] = " ";
}
setupListView();
if (savedInstanceState != null) {
stopwatchRunning = savedInstanceState.getBoolean("stopwatchRunning", false);
stopwatchTimes = savedInstanceState.getStringArray("stopwatchTimes");
stopwatchAdapter.notifyDataSetChanged();
} else {
stopwatchRunning = prefs.getBoolean("stopwatchRunning", false);
Log.d("savedPASS", String.valueOf(stopwatchRunning));
}
private void setupListView() {
if (lvStopwatch.getAdapter() == null) {
stopwatchAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, stopwatchTimes);
lvStopwatch.setAdapter(stopwatchAdapter);
}
registerForContextMenu(lvStopwatch);
}