使用cwc -endless适配器加载图像的无尽ListView



我编写了以下代码,使用CWAC无尽适配器实现了包含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来缓存从web加载的位图。问题是,在我的Nexus 7上测试时,我发现有很多缓存丢失,而Nexus 7应该有足够的可用内存。当我向上/向下滚动ListView时,这会导致图像弹出到位。

更糟糕的是,我看到应用程序崩溃与OutOfMemory错误,但我不能始终复制。

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

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

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

另一个选择是你可以使用通用图像加载器,它可以帮助你缓冲你的图像在磁盘(如SD card或你的应用程序的Internal memory)。这样Out of Memory的问题就可以解决了。

对于显示位图的最佳实践,有效地显示位图将有所帮助。

编辑:

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

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();

最新更新