I have a fragment that displays a list of up to several hundred items using a ListView. When the user causes a long-lasting scroll of the list and, while things are in motion, presses Back, bad things happen (a crash on a null pointer in getView() of the list adapter). So far, I was able to find the following workaround:
@Override
public void onDestroyView() {
super.onDestroyView();
// prevent a crash when Back is pressed while a long list is still being scrolled
mAdapter.clear();
Log.d(TAG, "Cleared adapter");
}
The trick is to make this work is to have the adapter use a clone of the source item list:
mAdapter = new ListAdapter((MyListType)mMyList.clone());
setListAdapter(mAdapter);
Otherwise, the call to mAdapter.clear() will wipe out the source item list, so when the fragment is recreated upon orientation change there will be no items on the list to display. However, a cloning of such a large number of items, even as a shallow copy, is an expensive operation, which I'd rather avoid.
As an alternative approach, in onDestroyView() I tried
mListView.setScrollContainer(false);
but it resulted in a crash as well.
Is there a better approach than the above workaround to achieve a clean destruction of a ListView with scrolling in progress? (Hint: trying to delay the fragment destruction by installing a listener to wait until the ListView stops scrolling is not acceptable -- the user wants an immediate response to a Back press.)