Why doesn't ArrayAdapter filter correctly after screen orientation change?
The layout is basic: an EditText at the top followed by a ListView. EditText has a TextWatcher.onTextChanged implemented so that ArrayAdapter.getFilter.filter is called with the entered text. ArrayAdapter's data is refreshed asynchronously on resume (see code snippet below). Easy enough, works just fine too... right up until the screen orientation is changed. Why would filtering suddenly break when the phone is turned sideways?
public class SometActivity extends ListActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
...
listAdapter = new ArrayAdapter<MemoryStatistic>(this, R.layout.list_item);
setListAdapter(listAdapter);
searchText = (EditText)findViewById(R.id.searchText);
searchText.addTextChangedListe开发者_如何学Pythonner(new TextWatcher()
{
@Override
public void onTextChanged(CharSequence text, int start, int before, int count)
{
listAdapter.getFilter().filter(text);
}
...
}
...
}
@Override
protected void onResume()
{
asyncRefreshListAdapter();//refresh the data asynchronously when activity is resumed
}
}
I thought I'd make this self-reply post in case other programmers who are new to Android development (like I am) become stumped by this. So, according to android reference onResume will only be called if Activity is
1) created
2) restarted
3) resumed (brought to foreground after resume)
Ok, so what does screen orientation have to do with this? Well, most devs who read documentation skim through it on the account of the fact that there's a lot to read and they just want to get to implementing something cool. I was no different. If only I had read further, I would've avoided a lot of headache later on:
Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed
And now it's obvious why filter wouldn't work correctly. The problem was that (once the activity was destroyed on screen orientation change) listAdapter wasn't fully or at all populated (due to the asynchronous nature of the refresh) before filtering would commence.
精彩评论