I'm maitaining code for an Android file view app, and after a minor modification, I encountered a very weird situation.
This app supports viewing the file system in a ListView, and this ListView is resued everytime the user navigate throught different directories. Before entering a sub-directory, current ListView position will be stored in a stack, and after the user back from the sub-directory, the position info will be popped from the stack, thus previous location can be restored.
Let me show you the original steps it performs after the user navigate back from a sub-dir to its parent, it uses a AsyncTask to perfrom the refresh:
in the onPreExecute() method, the current file list -- mFileNameList -- will be emptied, and a notifyDataSetChanged() operations follows.
in the doInBackground() method, the file list in the parent folder will be collected, and put in a list.
in the onPostExecute() method, the collected list be put in the mFileNameList, and after a notifyDataSetChanged() call, setSelectionFromTop() will put the ListView in the previous position before entering the subfolder.
Such mechanism works well before I maintain the source code. But I found a minor shortcoming in the process: in the onPreExecute(), the list will be emptied, so the ListView will be blank before showing the file list.
I thought such code is not necessary, so I removed the first step. But after testing, I found that setSelectionFromTop() will not position the ListView any more. Everytime the user back from the sub-directory, the ListView will always show the list from position 0, not from the previous position.
This is the code snippet that show the file list and restore the original position, but the mFileListView.setSelectionFromTop(item.pos, item.top) doesn't work any more.
@Override
protected void onPostExecute(ArrayList<FileInfo> result) {
mFileNameList.clear();
mFileNameList.addAll(result);
sortCurrentList(sort);
// other code
PathSelectionItem item = mFileViewInteractionHub.getLastPathListSelectionItem();
if (item != null && item.path.equals(
mFileViewInteractionHub.getCurrentPath())) {
mFileListView.setSelectionFromTop(item.pos, item.top);
}
I logged the backend stack, and found no error in the stack. Actually, I can setAdapter() before calling setSelectionFromTop(), and it will fix the bug. But I don't know why the setAdapter will do the trick.
Is there anybody can tell me what happened? Thanks.