Android Error加载图片视图

时间:2014-08-11 22:33:11

标签: android image-processing bitmap imageview bitmapfactory

我正在尝试在我的imageview中加载图片,但它没有为链接加载任何图像。 链接有图像,但我仍然得到空白空间。

private class LoadImage extends AsyncTask<String, String, Bitmap> {
    @Override
        protected void onPreExecute() {
            super.onPreExecute();
    }
       protected Bitmap doInBackground(String... args) {
         try {
               String url = "http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png";
               URL urlurl = new URL(url);
               bitmap = BitmapFactory.decodeStream(urlurl.openConnection().getInputStream());
        } catch (Exception e) {
              e.printStackTrace();
        }
      return bitmap;
       }
       protected void onPostExecute(Bitmap image) {
         if(image != null){
           img.setImageBitmap(image);
         }else{
           Toast.makeText(activity.getApplicationContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
         }
       }
   }

XML

 <ImageView
        android:id="@+id/list_image"
        android:layout_width="50dip"
        android:layout_height="50dip"
         />

1 个答案:

答案 0 :(得分:1)

正如您在logcat堆栈跟踪中看到的那样,您在mainthread异常上有一个网络,因为您在'main'线程上执行网络任务,也称为gui线程。您需要使用AsyncTask。

private class DownloadImageTask extends AsyncTask<Object, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(Object... args) {
        Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        return bmp;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
             //here do stuff with your bitmap data, also here you can interact with the gui
        }
    }

另外,我建议使用图像下载库从网上下载图像。它们使下载图像变得非常简单,您不必担心微小的细节。