【问题标题】:Set ImageView using URL使用 URL 设置 ImageView
【发布时间】:2013-05-05 20:55:00
【问题描述】:

我的服务器上有一张图片。图片的 URL 类似于: http://www.mydomain.com/123456uploaded_image.jpg

我正在尝试将此图像设置为我的 ImageView。这是我尝试过的代码:

    try{
            String url1 = myeventimagearray[position];
            URL ulrn = new URL(url1);
            HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
            InputStream is = (InputStream) con.getInputStream();
            Bitmap bmp = BitmapFactory.decodeStream(is);
            if (null != bmp)
                iveventimg.setImageBitmap(bmp);
            else
                Log.i("Image","Not set");

        } catch(Exception e) {
            e.printStackTrace();
        }

当我尝试这个时,我的图像视图是空的,即它没有设置图像视图,我在我的 logcat 中得到这个系统错误:

java.lang.ClassCastException: libcore.net.http.FixedLengthInputStream 无法转换为 com.example.eventnotifier.Base64$InputStream

Base46.java 是我从互联网上找到的一个文件,它对 Base64 表示法进行编码和解码。

知道为什么我会收到此 System.error 吗?

谢谢

【问题讨论】:

    标签: android imageview base64 android-imageview bitmapimage


    【解决方案1】:

    使用 URlImageViewHelper,它会负责将 url 加载到 imageview 中。

    Refer this

    它将自行处理缓存、后台加载等。

    【讨论】:

      【解决方案2】:

      这不是一个简单的答案,但您应该使用缓存系统。

      请参阅https://github.com/chrisbanes/Android-BitmapCache 以获得出色的信息!

      只需将 ImageView 换成 NetworkCacheableImageView,然后使用 loadImage( "http://....", true );

      【讨论】:

        【解决方案3】:

        您可能会遇到异常,因为您尝试在主线程上执行网络 io。考虑使用加载器或 AsyncTask 来加载图像。

        检查您的日志,我敢打赌您正在自动生成的 catch 块中打印堆栈跟踪。

         new Thread(new Runnable() {
           public void run() {
             final Bitmap b = bitmap = BitmapFactory.decodeStream((InputStream)new URL(myeventimagearray[position]).getContent());
             iveventimg.post(new Runnable() {
               public void run() {
                 iveventimg.setImageBitmap(b);
               }
            });
          }
        }).start();
        

        【讨论】:

        • 我编辑了帖子以详细解释错误。还是 cz im 在主线程上做网络 IO 吗?
        • 您得到的异常是出于其他原因。
        【解决方案4】:

        使用 Picasso 从 url 获取图像。在build.gradle和java中实现'com.squareup.picasso:picasso:2.71828'

        Picasso.get()
          .load(url) // http://www.example.com/123456uploaded_image.jpg
          .resize(50, 50)
          .centerCrop()
          .into(imageView)
        

        【讨论】:

          猜你喜欢
          • 2016-08-06
          • 1970-01-01
          • 2013-06-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-02
          相关资源
          最近更新 更多