Pourquoi ArrayAdapter filtre-t-il correctement après l'orientation de l'écran ne change-t-il pas?

StackOverflow https://stackoverflow.com/questions/3024243

Question

La mise en page est basique: un édition en haut suivi d'une liste. EditText a un textwatcher.ontextchange implémenté de sorte que ArrayAdapter.getFilter.filter est appelé avec le texte entré. Les données d'ArrayAdapter sont actualisées de manière asynchrone sur le CV (voir l'extrait de code ci-dessous). Assez facile, fonctionne très bien aussi ... jusqu'à ce que l'orientation de l'écran soit modifiée. Pourquoi le filtrage se casserait-il soudainement lorsque le téléphone est tourné sur le côté?

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.addTextChangedListener(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
    }
}
Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top