如何正确设置Volley以从URL下载图像

fei*_*ong 5 android caching bitmap android-volley

我知道Volley应该简单地下载和缓存图像,但是我一直在努力实现它.我已经浏览了网络以及有关凌空的stackoverflow上的许多文章,但我找到的所有示例似乎都不适合我.

我只想使用volley来下载和缓存来自给定URL的图像,而不是进行任何HTTP JSON REST处理.只需要获取给定的URL,下载位图并将它们设置为imageview,然后将它们添加到缓存中.

这是我迄今为止的最新尝试.如何正确加载和缓存图像?

if (data.getImageUrl() != null) {
        try {

            holder.thumbnail.setTag(data.getImageUrl());

        Cache cache = ImgController.getInstance().getRequestQueue().getCache();
        Cache.Entry entry = cache.get(data.getImageUrl());

            if (entry != null) {
                try {
                    String cImg = new String(entry.data, "UTF-8");
                    LruBitmapCache bitmapCache = new LruBitmapCache();
                    holder.thumbnail.setImageBitmap(bitmapCache.getBitmap(cImg));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            } else {

                ImageLoader imageLoader = ImgController.getInstance().getImageLoader();

                imageLoader.get(data.getImageUrl(), new ImageListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                        holder.thumbnail.setImageResource(R.drawable.filler_icon);

                    }

                    @Override
                    public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                        if (response.getBitmap() != null) {
                            // load image into imageview
                            holder.thumbnail.setImageBitmap(response.getBitmap());

                        }
                    }
                });
            }

            return convertView;
        } catch (Exception e) {
            e.printStackTrace();
            Log.v(DEBUG_TAG, "no image: ", e);
            holder.thumbnail.setImageResource(R.drawable.filler_icon);


        }
    }else {
        return null;
    }


    return convertView;
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到一个指向此行的NullPointerException

Cache cache = ImgController.getInstance().getRequestQueue().getCache();
Run Code Online (Sandbox Code Playgroud)

我已经设置了以下单例类来处理请求

public class ImgController extends Application {

public static final String TAG = ImgController.class.getSimpleName();
private RequestQueue requestQueue;
private ImageLoader imageLoader;

private static ImgController instance;

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

}
public static synchronized ImgController getInstance(){
    return instance;
}
public RequestQueue getRequestQueue(){
    if(requestQueue == null){
        requestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return this.requestQueue;
}
public ImageLoader getImageLoader(){
    getRequestQueue();
    if(imageLoader ==  null){
        imageLoader = new ImageLoader(this.requestQueue, new LruBitmapCache());
        }

    return this.imageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (requestQueue != null) {
        requestQueue.cancelAll(tag);
    }
}
Run Code Online (Sandbox Code Playgroud)

}

以及以下LruBitmapCache类

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {

public static int getDefaultLruCacheSize(){
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;

    return cacheSize;
}

public LruBitmapCache() {
    this(getDefaultLruCacheSize());
}
public LruBitmapCache(int maxSize) {
    super(maxSize);
}

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

@Override
public void putBitmap(String url, Bitmap bitmap) {
    put (url, bitmap);
}
Run Code Online (Sandbox Code Playgroud)

}

Cin*_*kyn 8

(抱歉英语能力差^^;)

Volley应该简单地下载和缓存图像

YEAH!排球非常简单.你不需要考虑缓存命中,图像加载等...

只是用NetworkImageView.贝鲁斯就是榜样.

layout_example.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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">

    <com.android.volley.toolbox.NetworkImageView
            android:id="@+id/photo"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_example);
    NetworkImageView nv = (NetworkImageView) findViewById(R.id.photo);
    nv.setDefaultImageResId(R.drawable.default_image); // image for loading...
    nv.setImageUrl(imageUrl, ImgController.getInstance().getImageLoader()); //ImgController from your code.
}
Run Code Online (Sandbox Code Playgroud)

NetworkImageView自动加载后台队列中的图像,并在分离此视图时取消请求using ImageLoader.并ImageLoader 自动使用内存lru缓存和磁盘缓存. NetworkImageView是最好的解决方案.

附加信息

NetworkImageView
       |
  ImageLoader (uses `LruBitmapCache` you implemented.)
       |
 RequestQueue (uses `DiskBasedCache`. it is already implemented in volley.)
Run Code Online (Sandbox Code Playgroud)


nef*_*tou 8

Volley可以使用图像请求的回调,您可以使用下面的代码.

    ImageView iv = null; /*Attach the Pointer for ImageView*/
    RequestQueue requestAdministrator = null; /*Attach the Pointer for Volley*/

    ImageRequest ir = new ImageRequest(url, new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            // callback
            iv.setImageBitmap(response);
        }
    }, 100, 100, null, null);
    // 100 is your custom Size before Downloading the Image.
    requestAdministrator.add(ir);
Run Code Online (Sandbox Code Playgroud)