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

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类应该是这样的,
        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);
            }
        }

关于java - Android-ViewRootImpl $ CalledFromWrongThreadException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10118301/

10-13 04:37