使用cwac-endless适配器加载无限的ListView图像

时间:2013-03-12 06:23:39

标签: android android-listview cwac-endless

我编写了以下代码,使用CWAC Endless Adapter实现了包含ImageViews的ListView的无限滚动。使用AsyncTasks按需从Web检索图像:

package com.myproject.ui.adapter;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.commonsware.cwac.endless.EndlessAdapter;

public class MyThumbsAdapter extends EndlessAdapter {

    public static class FetchThumbTask extends AsyncTask<String, Void, Bitmap> {

        private final Context mContext;
        private final BaseAdapter mAdapter;
        private final String mThumbId;
        private final View mView;

        public FetchThumbTask(Context context, BaseAdapter adapter, View view, String thumbId) {
            mContext = context;
            mAdapter = adapter;
            mView = view;
            mThumbId = thumbId;
        }

        @Override
        protected Bitmap doInBackground(String... arg0) {
            Bitmap bitmap = null;
            if (cache.get(mThumbId) == null) {
                // Fetch thumbnail
                try {
                    URL url = new URL(...);
                    InputStream is = url.openStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    cache.put(mThumbId, bitmap);
                } catch (Exception e) {
                    ...
                }
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
              // Set the loaded image on the ImageView
                      ImageView imageView = (ImageView) mView.findViewById(R.id.thumb_image);
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    public static class MyThumbsBaseAdapter extends BaseAdapter {

        private final Context mContext;
        private final List<String> mThumbIds = new ArrayList<String>();

        public MyThumbsBaseAdapter(Context context) {
            mContext = context;
        }

        public void addThumbIds(List<String> thumbIds) {
            mThumbIds.addAll(thumbIds);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            String thumbId = mThumbIds.get(position);
            View rootView = convertView;

            if (rootView == null) {
                rootView = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.thumbnails, null);
            }
            ImageView imageView =
                    (ImageView) rootView.findViewById(R.id.doodle_thumb_image);

            Bitmap bitmap = cache.get(thumbId);
            if (bitmap == null) {
                loadThumbBitmap(rootView, thumbId);
            } else if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }

            return rootView;
        }

        @Override
        public int getCount() {
            return mThumbIds.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        private void loadThumbBitmap(View view, String thumbId) {
            new FetchThumbTask(mContext, this, view, thumbId)
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    static {
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        int cacheSize = maxMemory / 8;
        cache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                return bitmap.getByteCount() / 1024;
            }
        };
    }

    private static final LruCache<String, Bitmap> cache;

    private List<String> mThumbIdsCache;

    public MyThumbsAdapter(Context context) {
        super(new MyThumbsBaseAdapter(context));
    }

    @Override
    protected View getPendingView(ViewGroup parent) {
        return LayoutInflater.from(parent.getContext())
                .inflate(R.layout.loading_thumb, null);
    }

    @Override
    protected boolean cacheInBackground() throws Exception {
        JsonReader reader = // Retrieve thumb ids list from server
        mThumbIdsCache = // Returned thumb ids list
        return true;
    }

    @Override
    protected void appendCachedData() {
        MyThumbsBaseAdapter adapter = (MyThumbsBaseAdapter) getWrappedAdapter();
        adapter.addThumbIds(mThumbIdsCache);
    }
}

我使用LruCache缓存从网络加载的位图。问题是我在Nexus 7上测试时看到大量缓存未命中,而Nexus 7应该有足够的可用内存。当我向上/向下滚动ListView时,这会导致图像弹出到位。

更糟糕的是,我看到应用程序因OutOfMemory错误而崩溃,但我无法一致地重现。

我在这里做错了什么?我不应该为每个图像触发单独的AsyncTasks吗?

编辑:我还应该提到我正在下载的图像是预先缩放的。

1 个答案:

答案 0 :(得分:1)

我认为你需要做的是在屏幕上显示Thumbnails而不是位图图像。您可以生成Thumbnails并根据您的尺寸要求进行显示。每当用户点击Thumb时,只需采用原始路径并设置壁纸。

另一种选择是您可以使用Universal Image Loader来帮助您缓存光盘中的图像(例如SD card或您应用的Internal memory)。因此Out of Memory的问题可以解决。

同样,为了显示位图的最佳做法,Displaying Bitmaps Efficiently会有所帮助。

修改

为您的应用程序使用以下配置。这将缓存应用程序的缓存目录中的图像。

File cacheDir = new File(this.getCacheDir(), "cwac");
if (!cacheDir.exists())
    cacheDir.mkdir();

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
            CWAC.this)
            .threadPoolSize(5)
            .threadPriority(Thread.MIN_PRIORITY + 3)
            .denyCacheImageMultipleSizesInMemory()
            // .memoryCache(new UsingFreqLimitedMemoryCache(2000000)) // You
            // can pass your own memory cache implementation
            .memoryCacheSize(1048576 * 10)
            // 1MB=1048576 *declare 20 or more size if images are more than
            // 200
            .discCache(new UnlimitedDiscCache(cacheDir))
            // You can pass your own disc cache implementation
            //.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            .build();