I have an Activity that begins executing an AsyncTask in response to clicking a Button widget. I disable the Button when it’s clicked using setEnabled(false). The AsyncTask calls a callback method on the Activity when it completes. I call setEnabled(true) on the Button in the callback to re-enable the Button when the AsyncTask is done. This all works fine until the orientation changes while the AsyncTask is executing. I’ve tried lots of different things to get the Button to be enabled/disabled properly when this happens and I can’t make it work right. What is the correct way to make this work even if the orientation changes while the AsyncTask is executing?
Share
I don’t believe you need to start intercepting orientation changes. Its cutting corners and its possibly going to cause you a lot of headaches if you actually want to do things like load different resources for different orientations.
The root problem is that the reference the AsyncTask has to the button that its meant to update is stale, it refers to your old button. What you can do to solve this is implement
Activity.onRetainNonConfigurationInstanceState(). This method is called in situations when an orientation change is happening and its to allow you to store items that are non-configuration specific, like running Threads.The other thing you need is a method in your AsyncTask to set the Button it should enable/disable. While your Activity is restarting you unset the Button and then reset it in onCreate().
The implementation might looks something like this.