【问题标题】:ListAdapter and background ThreadingListAdapter 和后台线程
【发布时间】:2015-06-16 17:19:46
【问题描述】:

我有一个 listadapter,其中有很多 listitems,每个 item 都包含一个 textview 和一个 imageview。我想从后端下载图片(Base64 编码),所以 Picasso 和 via URL 下载解决方案不适合我。 在我下载了 Base64 解码并且位图创建已经完成之后,我只是卡住了如何在列表适配器中启动后台线程,其中视图总是在回收(当用户滚动时)。

我开始使用 Hanlder 创建一个线程,其中处理程序将位图插入到图像视图中,但它没有工作(内存不足)。之后我触发了一个 AsyncTask,但在这种情况下我遇到了回收问题,namley:当用户向下滚动时,我在底部视图中看到顶部图像:(

使用改造进行下载

你能帮帮我吗?

我的 AsyncTaks 代码: 这里的问题,我更新了imageview,但是可能用户已经被滚走了!

public DownloadImageAsyncTask(ImageView iw, Display display, String imageID, ImagesCache imagesCache) {
    this.iw = iw;
    this.imageCache = imagesCache;
    this.imageID = imageID;
    this.display = display;
}
@Override
protected Void doInBackground(Void... params) {
    String[] imageArray = new String[1];
    imageArray[0] = imageID;
    ImageResponse imageResponse = new IdeaBackend().getImageByID(imageArray);
    bitmap = UserExperienceHelper.decodeBase64AndScaleDownImage(imageResponse.getResponse().get(0).getImageBase64Code(), display);
    imageCache.put(imageID, bitmap);

    return null;
}


@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    this.iw.setImageBitmap(bitmap);
}

【问题讨论】:

  • 您应该从 AsyncTask 发布代码,因为它可以部分工作。
  • 我已经编辑了问题:添加了异步任务代码
  • 您是否在适配器中实现了视图的回收?我认为这就是问题所在。
  • 你的意思是:来自 v7 支持库的 RecyclerView ?
  • 不。视图持有者模式。

标签: android multithreading android-bitmap


【解决方案1】:

在您的适配器中:

View listItemLayout = (View) inflater.inflate(...);
ImageView imageView = (ImageView) listItemLayout.findViewById(R.id.imageView);
MyImageLoader.loadImage(activity, imageView, id);

这是一个公共类,将为您完成图像的下载和缓存。

public class MyImageLoader {

    private HashMap < String, Bitmap > cache = new HashMap < String, Bitmap > ();

    public static loadImage(final Activity activity, final ImageView imageView, final String id) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (cache.containsKey(id) {
                    //Bitmap already exists. 
                } else {
                    //This bitmap has not been downloaded so you need to download the bitmap.
                    //Once bitmap is downloaded, add it to the HashMap.

                }

                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        imageView.setImageBitmap(cache.get(id));
                    }
                });
            }
        }).start();
    }
}

现在,无论您何时使用imageView.setImageBitmap(),图像都会自动更新。您不需要单独刷新视图。

对前面代码的一些补充:

public class MyImageLoader {

    private static HashMap <String, Bitmap> cache = new HashMap <String, Bitmap>();
    private static HashMap<String, DownloadListener> listeners = new HashMap()<>;
    private static ArrayList<String> currentlyDownloading = new ArrayList()<>;

    public static loadImage(final Activity activity, final ImageView imageView, final String id) {

        DownloadListener downloadListener = new DownloadListener(){
            @Override
            public void onDownloadComplete(){
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        imageView.setImageBitmap(cache.get(id));
                    }
                }); 
            }

            @Override
            public void onDownloadFailed(){
                // Do something when download fails. 
            }
        };

        if(!listeners.containsKey(id)){
            listener.put(id, new ArrayList<DownloadListener>());
        } 

        listener.get(id).add(downloadListener);

        if(cache.containsKey(id)){
            for(DownloadListener listener : listeners.get(id)){
                listener.onDownloadComplete();
            }                
        } else if(!currentlyDownloading.contains(id)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    currentlyDownloading.add(id);
                    //Start Downloading 
                    //Download finished
                    currentlyDownloading.remove(id);
                    //If download successful
                    cache.put(id, bitmap);
                    for(DownloadListener listener : listeners.get(id)){
                        listener.onDownloadComplete();
                    }  
                    /*
                    If download failed
                    for(DownloadListener listener : listeners.get(id)){
                        listener.onDownloadFailed();
                    }  
                    */
                    currentlyDownloading.remove(id);
                }
            }).start();
        }
    }

    public interface DownloadListener {

        public void onDownloadComplete();

        public void onDownloadFailed();
    }
}

【讨论】:

  • 我还没有尝试过代码,但我认为它应该可以工作。
【解决方案2】:

您需要回收位图或视图。可以轻松处理列表视图的增量加载。这里有一个帖子可能对你有帮助!

Optimized, Incremental Access to ListView.

Endless Scrolling with adapter views

【讨论】:

    【解决方案3】:

    首先,我要感谢您的 cmets 和有关解决方案的想法。 过去两天我正在研究这个问题,当我问你的时候,所以实际上我想出了我的最终解决方案,当我在这里发布时已经部分准备好了:

    public class IdeaAdapter extends ArrayAdapter<Idea> {
    
    private final Context context;
    private final Display display;
    private List<Idea> dataList;
    private Set<String> imagesInProgress;
    
    
    public IdeaAdapter(Display display, Activity c, List<Idea> dataList) {
        super(c, android.R.layout.simple_list_item_1, dataList);
        this.dataList = dataList;
        this.context = c;
        this.display = display;
        imagesInProgress = new HashSet<>();
    }
    
    
    @Override
    public int getCount() {
        return dataList.size();
    }
    
    @Override
    public Idea getItem(int position) {
        return dataList.get(position);
    }
    
    @Override
    public long getItemId(int position) {
        return position;
    }
    
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder vh;
        if (convertView == null) {
            vh = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.idea_list_item, null);
            vh.ideaImage = (ImageView) convertView.findViewById(R.id.idea_image);
            vh.ideaName = (TextView) convertView.findViewById(R.id.idea_title);
            vh.progressWheel = (ProgressWheel) convertView.findViewById(R.id.progress_wheel);
    
    
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
    
        final Idea ideaItem = dataList.get(position);
        vh.ideaName.setText(ideaItem.getTitle());
    
    
        if (ideaItem.getImages().size() > 0) {
            final String imageId = ideaItem.getImages().get(0);
            Log.e("  isContains", String.valueOf(ImagesCache.getInstance().containsKey(String.valueOf(imageId))));
    
            if (!ImagesCache.getInstance().containsKey(String.valueOf(imageId)) && !imagesInProgress.contains(imageId)) {
    
                Log.e("  downloading", String.valueOf(imageId));
    
                vh.ideaImage.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));
                imagesInProgress.add(imageId);
                new DownloadImageAsyncTask(vh.ideaImage, display, imageId).execute();
            } else {
                Log.e("CACHE", String.valueOf(imageId));
                vh.ideaImage.setImageBitmap(ImagesCache.getInstance().getBitmap(String.valueOf(imageId)));
            }
        }
    
    
        return convertView;
    }
    
    private static class ViewHolder {
        private ImageView ideaImage;
        private TextView ideaName;
        private ProgressWheel progressWheel;
    
    }
    

    }

    图像缓存:

    public class ImagesCache {
    private static ImagesCache INSTANCE;
    private static Context context;
    private static DiskLruCache mDiskCache;
    private static Bitmap.CompressFormat mCompressFormat = Bitmap.CompressFormat.JPEG;
    private static int mCompressQuality = 70;
    private static final int APP_VERSION = 1;
    private static final int VALUE_COUNT = 1;
    private static final String TAG = "DiskLruImageCache";
    private static final String uniqueName = "IdeasCache";
    private static final int diskCacheSize = 20*1024*1024; // in bytes
    
    /**
     * Make sure to give an application context to me.
     * I like to keep it as a static reference
     *
     * @param c
     */
    public static void init(Context c) {
        context = c;
    }
    
    public static ImagesCache getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new ImagesCache();
        }
        return INSTANCE;
    }
    
    private ImagesCache() {
        try {
            final File diskCacheDir = getDiskCacheDir(context, uniqueName);
            mDiskCache = DiskLruCache.open(diskCacheDir, APP_VERSION, VALUE_COUNT, diskCacheSize);
            /*mCompressFormat = compressFormat;
            mCompressQuality = quality;*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static boolean writeBitmapToFile(Bitmap bitmap, DiskLruCache.Editor editor)
            throws IOException {
        OutputStream out = null;
        try {
            out = new BufferedOutputStream(editor.newOutputStream(0), Utils.IO_BUFFER_SIZE);
            return bitmap.compress(mCompressFormat, mCompressQuality, out);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    
    private File getDiskCacheDir(Context context, String uniqueName) {
    
        // Check if media is mounted or storage is built-in, if so, try and use external cache dir
        // otherwise use internal cache dir
        final String cachePath =
                Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                        !Utils.isExternalStorageRemovable() ?
                        Utils.getExternalCacheDir(context).getPath() :
                        context.getCacheDir().getPath();
    
        return new File(cachePath + File.separator + uniqueName);
    }
    
    public static void put(String key, Bitmap data) {
    
        DiskLruCache.Editor editor = null;
        try {
            editor = mDiskCache.edit(key);
            if (editor == null) {
                return;
            }
    
            if (writeBitmapToFile(data, editor)) {
                mDiskCache.flush();
                editor.commit();
                if (BuildConfig.DEBUG) {
                    Log.d("cache_test_DISK_", "image put on disk cache " + key);
                }
            } else {
                editor.abort();
                if (BuildConfig.DEBUG) {
                    Log.d("cache_test_DISK_", "ERROR on: image put on disk cache " + key);
                }
            }
        } catch (IOException e) {
            if (BuildConfig.DEBUG) {
                Log.d("cache_test_DISK_", "ERROR on: image put on disk cache " + key);
            }
            try {
                if (editor != null) {
                    editor.abort();
                }
            } catch (IOException ignored) {
            }
        }
    
    }
    
    public static Bitmap getBitmap(String key) {
    
        Bitmap bitmap = null;
        DiskLruCache.Snapshot snapshot = null;
        try {
    
            snapshot = mDiskCache.get(key);
            if (snapshot == null) {
                return null;
            }
            final InputStream in = snapshot.getInputStream(0);
            if (in != null) {
                final BufferedInputStream buffIn =
                        new BufferedInputStream(in, Utils.IO_BUFFER_SIZE);
                bitmap = BitmapFactory.decodeStream(buffIn);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (snapshot != null) {
                snapshot.close();
            }
        }
    
        if (BuildConfig.DEBUG) {
            Log.d("cache_test_DISK_", bitmap == null ? "" : "image read from disk " + key);
        }
    
        return bitmap;
    
    }
    
    public static boolean containsKey(String key) {
    
        boolean contained = false;
        DiskLruCache.Snapshot snapshot = null;
        try {
            snapshot = mDiskCache.get(key);
            contained = snapshot != null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (snapshot != null) {
                snapshot.close();
            }
        }
    
        return contained;
    
    }
    
    public static void clearCache() {
        if (BuildConfig.DEBUG) {
            Log.d("cache_test_DISK_", "disk cache CLEARED");
        }
        try {
            mDiskCache.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static File getCacheFolder() {
        return mDiskCache.getDirectory();
    }
    

    }

    我需要做的就是管理线程(阻塞队列)以不为每个 getView 调用触发!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      相关资源
      最近更新 更多