我‘使用 Volley
进行互联网请求。我认为 onResponse
方法应该在收到响应时只调用一次,但我发现它调用了两次。
这是我的代码:
YVolley.getInstance(context).getImageLoader().get(category.child.get(i).icon, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Drawable drawable = new BitmapDrawable(context.getResources(), response.getBitmap());
drawable.setBounds(0, 0, GeneralUtil.dip2px(context, 45), GeneralUtil.dip2px(context, 45));
button.setCompoundDrawables(null, drawable, null, null);
Log.i("swifter", "get icon ... success == "+url);
}
@Override
public void onErrorResponse(VolleyError error) {
Log.i("swifter", "get drawable icon error...");
}
});
“成功”日志打印了两次。
是我的代码有问题还是应该是这样的?
最佳答案
我在 the documentation for ImageLoader.java
中找到了答案.文档指出:
The call flow is this:
Upon being attached to a request,
onResponse(response, true)
will be invoked to reflect any cached data that was already available. If the data was available,response.getBitmap()
will be non-null.After a network response returns, only one of the following cases will happen:
onResponse(response, false)
will be called if the image was loaded, oronErrorResponse
will be called if there was an error loading the image.
基于此,存在三种可能的响应模式。我已经在示例应用程序中测试并确认了这些。
图像是从缓存中加载的
在这种情况下会有一个调用:
onRespsonse(response, true)
将被调用,您可以从response.getBitmap()
获取图像。
图像不是从缓存加载,是从网络加载
在这种情况下会有两个调用:
首先,将调用
onRespsonse(response, true)
,并且response.getBitmap()
将为null
。然后,
onRespsonse(response, false)
将被调用,您可以从response.getBitmap()
获取图像。
图像不是从缓存加载的,也不是从网络加载的
在这种情况下会有两个调用:
首先,将调用
onRespsonse(response, true)
,并且response.getBitmap()
将为null
。然后,
onErrorResponse(error)
会被调用,错误的详细信息可以从error
中找到(这将是的一个实例VolleyError
).
在您的情况下,以下代码 fragment 将帮助您跳过第一个“空”响应:
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
// skip cache failure
if (isImmediate && response.getBitmap() == null) return;
// ...
}
希望这有助于弄清楚为什么您的请求可能会收到两个响应。
关于android - Volley, ImageLoader.ImageListener 中的 onResponse 调用了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216704/