5

I have a TabActivity with four tabs (each is its own Activity). Each tab defines its own onCreateOptionsMenu (and in some cases, onPrepareOptionsMenu). When each tab is loaded, an AsyncTask is kicked off to retrieve the data needed to populate that tab's list.

If I switch between tabs very quickly (while they're still loading) and then press the menu button (while the current tab's AsyncApiTask is still running), I'm able to get the wrong options menu to appear.

For example, let's say FooActivity (tab 1) has an options menu with a "Refresh" item, and BarActivity (tab 2) has an options menu with a "View All" item. If I start the app (with tab 1 active), quickly switch to tab 2, and then hit menu, the "Refresh" item (rather than the expected "View All" item) will sometimes show.

Furthermore, while this weird behavior sometimes occurs just on the first menu press (and later presses show the right items), sometimes it gets "stuck", and the wrong items show up on every press until I switch tabs.

Any idea what could be going on? I haven't heard of this happening before, and haven't been able to find any good suggestions.

jakeboxer
  • 3,300
  • 4
  • 26
  • 27
  • This is one of the seemingly infinite list of reasons why I detest using activities as the contents of tabs. Make your tabs be simple Views, and have your *single* `onPrepareOptionsMenu()` delegate to an implementation based on the active tab. – CommonsWare Apr 25 '10 at 11:39
  • Ah excellent, it's extremely comforting to know that I'm not doing something horribly wrong to cause this. I'll consider this solution. Thanks! – jakeboxer Apr 26 '10 at 00:36

1 Answers1

0

Yes, CommonsWare suggestion is a better solution! You could even consider using FragmentTabHost and fragments for each tab. That way the host activity can update the options menu centrally from onTabChanged(String tab).

While an AsyncTask is spawned from an Activity, if it hasn't run onPostExecute(...) it is still going. Also, since the default behavior of AsyncTasks is variable (different versions of android run them sequentially/parallel), it's hard to control without your own ThreadPoolExecutor. Your quick Activity switching and repeated AsyncTasks seem to be blocking.

adityajones
  • 601
  • 1
  • 4
  • 10