当我从parse.com检索图像时如何修复android.os.NetworkOnMainThreadException?

时间:2016-04-09 17:31:55

标签: android parse-platform

我有一个上传并从parse.com上获取图片的应用程序

我有android.os.NetworkOnMainThreadException任何人都可以帮助我并告诉我如何解决它?

谢谢

    final ParseFile fileObject = (ParseFile) parseObject.get("ImageFile");

    URL url = new URL(fileObject.getUrl());

    Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    imageView.setImageBitmap(bmp);

    linearLayout.addView(imageView);

2 个答案:

答案 0 :(得分:0)

使用您最喜欢的image-loading library,例如Picasso,在后台下载图片并异步填充ImageView

或者,做自己的后台工作(例如,AsyncTask)在后台线程上下载图像,然后更新主应用程序线程上的ImageView,以及处理缓存等等。

您的final ParseFile fileObject = (ParseFile) parseObject.get("ImageFile");代码也可能需要在后台完成;我没有使用Parse,因此不知道其API的细节。

答案 1 :(得分:0)

Upload and Download Image(like Time consuming process) you should do that in Background thread.You tried to get or upload images in Main thread so got android.os.NetworkOnMainThreadException.Use Async task to do that

class ImageDownload extends AsyncTask<Object, Void, Object>
    {

        Bitmap myBitmap=null;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            //ShowDialog();
        }

        @Override
        protected Object doInBackground(Object... params)
        {
           final ParseFile fileObject = (ParseFile) parseObject.get("ImageFile");

    URL url = new URL(fileObject.getUrl());

    Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());

            return null;
        }

        @Override
        protected void onPostExecute(Object result)
        {
            super.onPostExecute(result);


            HideDialog()

           //Update UI here
           linearLayout.addView(imageView);
           imageView.setImageBitmap(bmp);

        }

    }