开发者

Problems with AsyncTask and updating UI with ProgressUpdate and Listeners

I am getting a "CalledFromWrongThreadException" error when I try to update a TextView (via a listener) from an AsyncTask onProgressUpdate.

If I try to update the same TextView from onPostExecute everything works.

I have been testing using code based on https://github.com/commonsguy/开发者_Go百科cw-android/tree/master/Service/WeatherAPI

(with a small mod that does an onProgressUpdate in the doInBackgroundMethod, and adds the onProgressUpdate override)

Any suggestion to fixes would be most appreciated.


Are you calling onProgressUpdate() from your code? You shouldn't do it. Use publishProgress() method.


onProgressUpdate doesn't run on UI thread, so you can't access views from this method. If you want to update progress, you should find a way to synchronize your AsyncTask with your activity. A way that I'm using is to create an interface with methods like onBegin, onUpdate and onFinish. You should implement this interface in your main activity class. Then you should have an instance of your activity inside your AsyncTask. In the onProgressUpdate method you just call the onUpdate method in your activity and update the layout. Hope I've explained it clear enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜