CalledFromWrongThreadException

CalledFromWrongThreadException

本文介绍了Android - ViewRootImpl$CalledFromWrongThreadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 this 来显示来自互联网的图像但它会引发如下错误:
04-12 13:45:05.337: E/AndroidRuntime(27897): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能触摸其视图.

I was using this, to DISPLAY IMAGES FROM THE INTERNET but it throws an error as below:
04-12 13:45:05.337: E/AndroidRuntime(27897): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

public class Order extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            new DownloadFilesTask().execute();       
        }    
        private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
            protected void onPostExecute(Void result) {
            }
             @Override
             protected Void doInBackground(Void... params) {
                 setContentView(R.layout.order);
                    ImageView imageView = (ImageView)findViewById(R.id.imgView);  
                    imageView.setImageDrawable(createDrawableFromURL("http://savagelook.com/misc/sl_drop2.png"));
                    return null;
             }          
        }     
        private Drawable createDrawableFromURL(String urlString) {
            Drawable image = null;
        try {
            URL url = new URL(urlString);
            InputStream is = (InputStream)url.getContent();
            image = Drawable.createFromStream(is, "src");
        } catch (MalformedURLException e) {
            image = null;
        } catch (IOException e) {
            image = null;
        } 
        return image;
        }

}

推荐答案

把这个放到onCreate()

ImageView imageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order);
        imageView = (ImageView)findViewById(R.id.imgView);
        new DownloadFilesTask().execute();       
    } 

而你的 AsyncTask 类应该是这样的,

And your AsyncTask class should be like this,

        private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
             Drawable drawable;

             @Override
             protected Void doInBackground(Void... params) {
             drawable = createDrawableFromURL(
                                   "http://savagelook.com/misc/sl_drop2.png");
              return null;
             }
             protected void onPostExecute(Void result) {
                    imageView.setImageDrawable(drawable);
            }          
        } 

这篇关于Android - ViewRootImpl$CalledFromWrongThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:24