在Android平台

时间:2015-12-04 21:23:15

标签: android caching android-volley

我使用GridView下载数据并将其显示在两列上。我正在使用Volley Library下载数据。我能够获取和解析图像并将它们放在网格视图上,一切正常。

但是,当用户向上和向下滚动时,会发生网络操作并反复重新加载图像。有没有办法缓存它们,以防止一次又一次地下载图像。我是Android环境的新手。

我在iOS中使用AFNetworking实现了相同功能,它就像魅力一样,但我不确定Android平台中缺少什么。我以为Volley Library处理缓存操作。

   <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="#ffffff">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="2dp"
        android:horizontalSpacing="2dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</RelativeLayout>

MainActivity

JsonArrayRequest request = new JsonArrayRequest(Config.PRODUCT_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                            try {
                                List<ImageRecord> imageRecords=parse(response);
                                mAdapter.swapImageRecords(imageRecords);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d("Unable to fecth","yes");
                    }
                });
        CustomVolleyRequest.getInstance(this).getRequestQueue().add(request);

我有以下Singleton类。

  public class CustomVolleyRequest {

    private static CustomVolleyRequest customVolleyRequest;
    private static Context context;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;


    private CustomVolleyRequest(Context context) {
        this.context = context;
        this.requestQueue = getRequestQueue();

        imageLoader = new ImageLoader(requestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized CustomVolleyRequest getInstance(Context context) {
        if (customVolleyRequest == null) {
            customVolleyRequest = new CustomVolleyRequest(context);
        }
        return customVolleyRequest;
    }

    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new HurlStack());
            requestQueue = new RequestQueue(cache, network);
            requestQueue.start();
        }
        return requestQueue;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}

grid_item.XML

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

ProductMainAdapter.XML

public class ProductMainAdapter extends ArrayAdapter<ImageRecord> {
    private ImageLoader mImageLoader;
    private RequestQueue mRequestQueue;

    public ProductMainAdapter(Context context) {
        super(context, R.layout.grid_item);
        mRequestQueue = Volley.newRequestQueue(context);
        mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(10);
            public void putBitmap(String url, Bitmap bitmap) {
                mCache.put(url, bitmap);
            }
            public Bitmap getBitmap(String url) {
                return mCache.get(url);
            }
        });
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item, parent, false);
        }

        NetworkImageView imageView = (NetworkImageView) convertView.findViewById(R.id.picture);
        TextView textView = (TextView) convertView.findViewById(R.id.text);

        ImageRecord imageRecord = getItem(position);

        imageView.setImageUrl(imageRecord.getUrl(),mImageLoader);
        textView.setText(imageRecord.getTitle());

        return convertView;
    }
    public void swapImageRecords(List<ImageRecord> objects) {
        clear();

        for(ImageRecord object : objects) {
            add(object);
        }

        notifyDataSetChanged();
    }
}

1 个答案:

答案 0 :(得分:0)

有一个名为 Picasso 的图书馆,可让您将图像缓存到Android设备。 它的另一个美妙之处在于,当您使用listview或gridview时,它将处理,下载和停止缓存过程本身。 让我们以listview适配器为例,如果您要使用Picasso将图像显示到列表视图,当列表子项可见或隐藏时,Picasso会自动处理缓存的缓存和取消。 http://square.github.io/picasso/

我在其上写了一篇文章here

希望它有所帮助。