下载图像和更新listView

时间:2016-04-06 03:07:10

标签: android listview runnable executorservice

我遇到了下载图像和更新ImageView的问题,我正在使用ExecutorServices下载图像,但我遇到的问题是,在场景中,我使用基本适配器在列表中显示Imageview。图像被下载但两个图像仅在firstImage View中更新。

所以Bitmap在同一个imageView中得到更新,任何人都面临类似的问题

例如,我正在下载2个图像,它正在创建2个ImageDownloader实例,所有运行良好,直到该类的Run()在下载部分之前的行中,一旦Image下载,我得到的对象参考第一个Image Downloader类的ImageView,我不知道为什么?我认为它与listview或者适配器无关,它与Executor和Runnable Implementation更相关,

public class ImageLoader {

ExecutorService mExecutorService = null;
static ImageLoader mLoader = null;
Handler mImageHandler = null ;
DisplayMetrics mDisplayMetrics = null;
int mRequiredWidth =0 , mRequiredHeight = 0;
Map<String,ImageView> mToLoadObjects = Collections.synchronizedMap(
        new WeakHashMap<String, ImageView>());
ArrayList<String> toloadURL = new ArrayList<String>();
protected Resources mResources = null;
MyImageCache mMemoryCache;
Activity activity;
public static final String LOGGER = "ImageLoader";

public ImageLoader(Activity context){
  mExecutorService = Executors.newFixedThreadPool(5);
  mImageHandler = new Handler();
  mResources = context.getResources();
  activity = context;
  mMemoryCache  = new MyImageCache();
  mDisplayMetrics  = context.getResources().getDisplayMetrics();
  mRequiredWidth = mDisplayMetrics.widthPixels;
  mRequiredHeight = mDisplayMetrics.heightPixels;

}



public void loadImage (String url,ImageView imageView){     
    try {
        if (imageView != null) {
           if (!toloadURL.contains(url)) {
                toloadURL.add(url);
                mExecutorService.execute(new ImageDownloader(url,imageView));
            } 
        }
    }catch (Exception e){
        Log.v("Exception Occurs>>",""+e.getMessage());
    }
}




class ImageDownloader implements  Runnable{
    String imageUrl;
    ImageView downloadableImageView;
    ImageDownloader loader;


    ImageDownloader(String url,ImageView view){
        Log.v(LOGGER,"Within ImageDownloader "+url +"this>>>"+this);
        loader = this;
        imageUrl = url;
        downloadableImageView  = view;
        Log.v(LOGGER,"Within ImageDownloader "+downloadableImageView.getTag()+"this>>>"+this);
    }

    @Override
    public void run() {
        Log.v(LOGGER, "run" + downloadableImageView.getTag()+"this>>>>>"+this);
        Bitmap tempBitmap = null;
        tempBitmap = (mMemoryCache.getBitmapFromMemCache(imageUrl));
        try{
            if(tempBitmap!=null){
                Log.v(LOGGER,"ImageBitmap Wid>>>>>>"+downloadableImageView.getTag()+"this>>>>"+this+""+tempBitmap.getWidth());
                Log.v(LOGGER,"ImageBitmap Ht>>>>>>"+downloadableImageView.getTag()+ "this>>>>"+this+""+tempBitmap.getHeight());
                downloadableImageView.setImageBitmap(tempBitmap);
            }else{
                Log.v(LOGGER, "else to download Tag is" + downloadableImageView.getTag()+"this>>>>>"+this);//Works till this point

                final Bitmap tempBitmap1 = getBitmap(imageUrl);
                Log.v(LOGGER, "else to download Tag is " + downloadableImageView.getTag() + "After Download>>>" + tempBitmap1.getWidth() + "this>>>>>" + this);//Issue happens here
                mMemoryCache.addBitmapToMemoryCache(imageUrl, tempBitmap1);
                Log.v("LOGGER, else to download Tag is "+downloadableImageView.getTag()+"After Cache>>>", "" + downloadableImageView.getTag()+"this>>>>"+this);
                if(tempBitmap1!=null){
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.v("LOGGER, else to download Tag is "+downloadableImageView.getTag()+"RunOnUIThread>>>", "" + downloadableImageView.getTag()+"this>>>>"+loader);
                            downloadableImageView.setImageBitmap(tempBitmap1);
                            downloadableImageView.requestLayout();
                        }
                    });
                }
            }
        }catch(Exception e){
            Log.v("ExceptionBitmap",""+e.getMessage());
        }

    }

    public Bitmap getBitmap(String imageUrl){
        Bitmap bitmap=null;
        try {
            Log.v("Within getBitmap ","run");
            URL uri = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection)uri.openConnection();
            connection.setInstanceFollowRedirects(true);
            //bitmap = BitmapFactory.decodeStream(connection.getInputStream());
             bitmap = decodeSampledBitmapFromInputStream(connection.getInputStream(), mRequiredWidth, mRequiredHeight);

        } catch (Exception e) {
           Log.v("ExceptionLoad",""+e.getMessage());
        }
        return bitmap;
    }
}

public  Bitmap decodeSampledBitmapFromInputStream(InputStream in
                                                        , int reqWidth, int reqHeight) {

    InputStream copyiInputStream1 = null;
    InputStream copyiInputStream2 = null;
    try {
        byte[] data = InputStreamTOByte(in);
        copyiInputStream1 = byteTOInputStream(data);
        copyiInputStream2 = byteTOInputStream(data);
    } catch (Exception e) {
        e.printStackTrace();
    }
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(copyiInputStream1, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeStream(copyiInputStream2, null, options);
}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

public InputStream byteTOInputStream(byte[] in) throws Exception{

    ByteArrayInputStream is = new ByteArrayInputStream(in);
    return is;
}

public byte[] InputStreamTOByte(InputStream in) throws IOException {

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] data = new byte[1024*16];
    int count = -1;
    while((count = in.read(data,0,1024*16)) != -1)
        outStream.write(data, 0, count);

    data = null;
    return outStream.toByteArray();
}


class BitmapUpdater implements Runnable
{
    Bitmap bitmap;
    ImageView imageView;

    public BitmapUpdater(Bitmap bitmap, ImageView imageView){
        bitmap=bitmap;
        imageView =imageView;
    }
    public void run()
    {
        // Show bitmap on UI
        if(bitmap!=null){
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageBitmap(bitmap);
                }
            });
        }
        else
            imageView.setImageResource(R.drawable.account_photo_book_detail2);
    }
}

}

我已附上日志以供参考,请帮助解决此问题

Image Tag(0,1)--> I applied Tag for ImageView to sort out the Image View instance

线程1:(ImageDownloader1线程对象)

04-06 17:05:57.662 20053-20053 / com.xxx.xxxxmobileapp V / ImageLoader:在ImageDownloader https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s1024/Antelope%252520Hallway.jpgthis&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader $ ImageDownloader @ 435058b0 04-06 17:05:57.662 20053-20053 / com.xxx.xxxxmobileapp V / ImageLoader:在ImageDownloader 0(imageViewObjectTag)中,这是&gt;&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader $ ImageDownloader @

04-06 17:05:57.664 20053-20130 / com.xxx.xxxxmobileapp V / ImageLoader:否则下载Tag is0(imageViewObjectTag)这个&gt;&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook。 network.ImageLoader$ImageDownloader@435058b0

线程2:((ImageDownloader2线程对象))

04-06 17:05:57.666 20053-20053 / com.xxx.xxxxmobileapp V / ImageLoader:在ImageDownloader https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s1024/Another%252520Rockaway%252520Sunset.jpgthis&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader $ ImageDownloader @ 431a5d58 04-06 17:05:57.666 20053-20053 / com.xxx.xxxxmobileapp V / ImageLoader:在ImageDownloader 1(imageView)中,这是&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@431a5d58

线程1&amp; 2 run():

20053-20130 / com.xxx.xxxxmobileapp V / ImageLoader:运行0(imageViewObjectTag)这个&gt;&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@435058b0 20053-20131 / com.xxx.xxxxmobileapp V / ImageLoader:运行1(imageViewObjectTag)这个&gt;&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@431a5d58

否则下载Tag is1this&gt;&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@431a5d58

((ImageDownloader1线程对象))下载后:

否则下载标签为0(imageViewObjectTag)下载后&gt;&gt;&gt;&gt; 1024this&gt;&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@435058b0 //(ImageDownloader1对象) ) 否则下载Tag为0(imageViewObjectTag)After Cache&gt;&gt;&gt;:0这个&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@435058b0 //(ImageDownloader1 Object)) 否则下载标签为0(imageViewObjectTag)RunOnUIThread&gt;&gt;&gt;:0这个&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@435058b0 //(ImageDownloader1对象))

一切都好,直到这一点

((ImageDownloader2线程对象))下载后:

否则下载标签为0(imageViewObjectTag)下载&gt;&gt;&gt; 1024this&gt;&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@431a5d58 //(ImageDownloader2对象包含ImageView标签变为0不同,应该是tag1)) 否则下载Tag为0(imageViewObjectTag)After Cache&gt;&gt;&gt;:0this&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@431a5d58 //(带有ImageView标签的ImageDownloader2对象来自0个不同的应该是tag1)) 否则下载标签为0(imageViewObjectTag)RunOnUIThread&gt;&gt;&gt;:0这个&gt;&gt;&gt;&gt; com.xxx.xxxxmobileapp.Imagebook.network.ImageLoader$ImageDownloader@431a5d58 //(ImageDownloader2对象,ImageView标签为0不同的应该是tag1))

5 个答案:

答案 0 :(得分:4)

为什么不使用Glide库进行图像下载?

它只需一行即可完成所有事情。

这是它的语法

Glide.with(context).load(URL).into(Imageview);

答案 1 :(得分:1)

我认为这是一个回收问题,问题是在下载完成后,初始ImageView可能代表列表中的另一个位置。你看到问题发生在getBitmap(imageUrl)调用之后,但从理论上讲,它也可能更早发生。我不确定您的代码中是否使用了BitmapUpdater,但初看起来,这与您的情况无关。

因此,为了解决此问题,您需要实现一种机制,以避免使用“旧”位图更新ImageView。您可以使用tag的{​​{1}}属性来保存需要显示的实际URL。如果图像ImageView中的URL与实际用于下载的URL不同,则只需缓存图像。你可以做点什么

tag

public void loadImage (String url,ImageView imageView){
    if(imageView != null) imageView.setTag(url);
    [...]
}

另外,我建议避免使用if(tempBitmap1!=null){ activity.runOnUiThread(new Runnable() { @Override public void run() { Log.v("LOGGER, else to download Tag is " + downloadableImageView.getTag()+"RunOnUIThread>>>", "" + downloadableImageView.getTag()+"this>>>>"+loader); if(downloadableImageView.getTag().equals(imageUrl) { downloadableImageView.setImageBitmap(tempBitmap1); } else Log.v(LOGGER, "the image no longer wants this URL, ignoring"); //downloadableImageView.requestLayout(); } }); } ,因为它会导致整个布局被测量,在您的情况下,不需要它。

答案 2 :(得分:1)

是的,最终我通过我的朋友arunkumar

解决了问题

感谢他:)

我尝试了两件事,

1)找出问题是列表视图或执行器服务实现。要找出我用线性布局替换列表视图并添加为成功工作的视图,这确认问题是listview而不是执行器服务实现。

2)图像在第一张图片中更新的真正问题是因为视图ID(ImageView.getID())相同,

我设置了ID而不是设置标签,我将id传递给了图像加载器类,我通过findViewById(SetID)检索了图像,这是有用的

我正在添加一些有用的代码

用于在适配器类中设置ID:

 final ImageView imageView = holder.jobImageView;
       holder.jobImageView.setId(position);
       loader.loadImage(object.getlargeImageUrl(),holder.jobImageView,position);

获取适配器类中的ID:

final Bitmap tempBitmap1 = getBitmap(imageUrl);
                Log.v(LOGGER, "else to download Tag is " +imageViewId + "After Download>>>" + tempBitmap1.getWidth() + "this>>>>>" + this);
                mMemoryCache.addBitmapToMemoryCache(imageUrl, tempBitmap1);
                downloadableImageView = (ImageView)activity.findViewById(imageViewId);
                Log.v("LOGGER, else to download Tag is "+downloadableImageView.getTag()+"After Cache>>>", "" + downloadableImageView.getTag()+"this>>>>"+this);
                if(tempBitmap1!=null){
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.v("LOGGER, else to download Tag is " + downloadableImageView.getTag() + "RunOnUIThread>>>", "" + downloadableImageView.getTag() + "this>>>>" + loader);

                            downloadableImageView.setImageBitmap(tempBitmap1);
                            //downloadableImageView.requestLayout();
                        }
                    });
                }

答案 3 :(得分:0)

您可以使用Picasso图像加载库 链接以获取Picasso

的文档

答案 4 :(得分:0)

如果在本地存储或在线流中解码大位图这样繁重的工作,我们必须在工作线程中完成,问题是在完成解码后,imageview已被回收。解决它:

// In your adapter (onCreateView)
bitmap = yourBitmapCache.get(position);
if (bitmap != null)
    yourImageView.setImageBitmap(bitmap);
else if (imageLoaderManager.isLoading.get(position) == false){
    imagerLoaderManager.load(position, url);
}


// Create Callback interface
interface Callback {
     void onFinishLoad(int position, Bitmap bm);
}

// Create inner class ImageLoaderManager
class ImageLoaderManager {
    Hasmap<Integer, Boolean> isLoading = new Hasmap<>();
    Callback callback = new Callback() {
         @Override
         void onFinishLoad(int position, Bitmap bitmap){
             isLoading.put(position, false);
             if (bitmap != null) {
                  yourBitmapCache.put(position, bitmap)
                  activity.runOnUiThread(new Runnable() {
                       @Override
                       public void run(){
                            notifyDataSetInvalidated();
                            // If you use recycler view adapter: notifyItemChanged(position)
                       }
                  });

             }
         }
    };

    public void load(int position, String url){
         isLoading.put(position, true);
         newYourImageLoader(url, position, callback).start();
         // when loader finish job, 
         // it's must call back using callback.onFinishLoad(given position, bitmap result);
    }
}

无需在我的解决方案中保留ImageView引用。只需记住position并要求适配器在解码任务完成后重新加载此位置的项目视图,现在yourBitmapCache中已存在位图。