EDIT - Please read first!
It turns out that I was making a very stupid mistake. My layout contains a WebView that has the exact same background color as the ListView. The WebView is hidden at some point after the activity loads, but I forgot to hide it after an orientation change, so it covered the ListView and it made it seem like it was empty, when in fact it had been loaded correctly. I'll leave this question here as it provides a working example on how to restore ListView data after an orientation change :)
---------------------------------
Well, this seemed pretty easy at the time. I'm trying to restore the data on a ListView after an orientation change. The data is fetched from a web service, so at first I was simply calling the web service after the change took place. This was working fine, but re-fetching the data is way too slow for so simple a situation, so I thought that I would rather save the ListView's state and then just restore it without having to go back to the server.
I'm doing this with onSaveInstanceState:
protected void onSaveInstanceState (Bundle outState) {
ListAdapter adapter = this.listView.getAdapter();
if (adapter != null) {
try {
String dataSource = ((JSONArrayAdapter)adapter).getDataSource().toString(1);
outState.putString("dataSource", dataSource);
} catch (Exception e) {
Log.w("MainActivity", "Invalid data adapter", e);
}
}
}
JSONArrayAdapter is a custom adapter that I'm using, which works with JSONArray objects as its data source. I know that it works since it displays everything correctly before the orientation change.
After saving the ListView data as a JSON string, I try to restore it with onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
String dataSource = null;
if (savedInstanceState != null) {
dataSource = savedInstanceState.getString("dataSource");
}
if (dataSource == null) {
reloadList(); //this is a call to the web service
} else {
try {
JSONArray array = new JSONArray(dataSource);
this.listView.setAdapter(new JSONArrayAdapter(getApplicationContext(), array));
this.progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
Log.w("MainActivity", "Invalid data adapter", e);
reloadList();
}
}
}
The result is that I flip the device and there are no errors, but the ListView is empty (or its items are invisible at least). Using the debugger, I've verified that the JSON string is stored correctly. I've even stepped through the getView method on the adapter to make sure that the views are generated correctly. It is also worth noting that the code is not entering any of the catch blocks. Does anyone know what could be causing the ListView to be empty? Thanks