I have an Activity which starts an AsyncTask. This AsyncTask uses AutoCompleteTextView.showDropDown() in onPostExecute. The problem is when AsyncTask is running, I press “Back” and the application throws exception at showDropDown() line because AsyncTask is still using AutoCompleteTextView. How to fix this problem? (the best way)
Update: I’m still not satisfied with the solution of sonykuba. It is not a good practice when using non-final static variable. I want to decouple AsyncTask from the Activity but can’t think out any better solutions for this.
Update: Add exception
09-05 13:41:05.536: ERROR/AndroidRuntime(962): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at android.view.ViewRoot.setView(ViewRoot.java:505)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at android.view.Window$LocalWindowManager.addView(Window.java:424)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at android.widget.PopupWindow.invokePopup(PopupWindow.java:828)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:740)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at android.widget.AutoCompleteTextView.showDropDown(AutoCompleteTextView.java:1207)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at com.megadict.business.recommending.RecommendTaskInitializer$2.onPostExecute(RecommendTaskInitializer.java:58)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at com.megadict.business.recommending.AbstractRecommendTask.onPostExecute(AbstractRecommendTask.java:29)
09-05 13:41:05.536: ERROR/AndroidRuntime(962): at com.megadict.business.recommending.RecommendTask.onPostExecute(RecommendTask.java:37)
I had a solution. The owner of AsyncTask has a function:
When I need to use it, I will check if it is null. If not, call showDropDown().
When Activity destroys, I set it to null.