【问题标题】:Android Error loading image viewAndroid 加载图像视图时出错
【发布时间】:2014-10-04 21:13:22
【问题描述】:

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

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"
         />

【问题讨论】:

    标签: android image-processing bitmap imageview bitmapfactory


    【解决方案1】:

    正如您在 logcat 堆栈跟踪中看到的,您在主线程异常上有一个网络,因为您正在“主”线程上执行网络任务,该线程也称为 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
            }
        }
    

    我还建议使用图像下载库从网络上下载图像。它们使下载图像变得非常容易,您不必担心这些微小的细节。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多