Android 如何正确设置截取以从URL下载图像
我知道Volley应该让下载和缓存图像变得简单,但我一直在为正确实现它而奋斗数小时。我已经在网上查阅了很多关于stackoverflow的关于截击的文章,但是我发现没有一个例子适合我 我只想使用volley从给定的url下载和缓存图像,而不是进行任何HTTP JSON REST处理。只需获取给定的URL,下载位图并将其设置为imageview,然后将其添加到缓存中 这是我迄今为止的最新尝试。 如何正确加载和缓存带有截取的图像Android 如何正确设置截取以从URL下载图像,android,caching,bitmap,android-volley,Android,Caching,Bitmap,Android Volley,我知道Volley应该让下载和缓存图像变得简单,但我一直在为正确实现它而奋斗数小时。我已经在网上查阅了很多关于stackoverflow的关于截击的文章,但是我发现没有一个例子适合我 我只想使用volley从给定的url下载和缓存图像,而不是进行任何HTTP JSON REST处理。只需获取给定的URL,下载位图并将其设置为imageview,然后将其添加到缓存中 这是我迄今为止的最新尝试。 如何正确加载和缓存带有截取的图像 if (data.getImageUrl() != null) {
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;
}
当我运行它时,我得到一个指向这行的NullPointerException
Cache cache = ImgController.getInstance().getRequestQueue().getCache();
我已经设置了以下singleton类来处理请求
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);
}
}
公共类ImgController扩展应用程序{
公共静态最终字符串标记=ImgController.class.getSimpleName();
私有请求队列请求队列;
私有图像加载器;
私有静态ImgController实例;
@凌驾
public void onCreate(){
super.onCreate();
实例=此;
}
公共静态同步ImgController getInstance(){
返回实例;
}
公共请求队列getRequestQueue(){
if(requestQueue==null){
requestQueue=Volley.newRequestQueue(getApplicationContext());
}
返回此.requestQueue;
}
公共ImageLoader getImageLoader(){
getRequestQueue();
如果(imageLoader==null){
imageLoader=新的imageLoader(this.requestQueue,new lRubitMacache());
}
返回此.imageLoader;
}
公共无效addToRequestQueue(请求请求,字符串标记){
//如果标记为空,则设置默认标记
请求setTag(TextUtils.isEmpty(tag)?tag:tag;
getRequestQueue().add(请求);
}
公共无效addToRequestQueue(请求请求){
要求设置标签(标签);
getRequestQueue().add(请求);
}
公共作废取消挂起请求(对象标记){
if(requestQueue!=null){
requestQueue.cancelAll(标记);
}
}
}
以及下面的lRubitMacache类
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);
}
公共类LruBitmapCache扩展LruCache实现ImageLoader.ImageCache{
公共静态int getDefaultLruCacheSize(){
final int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);
最终int cacheSize=maxMemory/8;
返回缓存大小;
}
公共LRubitMacache(){
这个(getDefaultLruCacheSize());
}
公共LruBitmapCache(int-maxSize){
超级(最大尺寸);
}
@凌驾
公共位图getBitmap(字符串url){
返回get(url);
}
@凌驾
公共位图(字符串url、位图){
put(url、位图);
}
}(很抱歉英语水平差^^;)
截击应该使下载和缓存图像变得简单
是啊!截击很简单。你不需要考虑缓存命中,图像加载等
只需使用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>
NetworkImageView
使用ImageLoader从后台队列自动加载图像,并在分离此视图时取消请求。和ImageLoader
自动使用内存lru缓存和磁盘缓存。NetworkImageView
是您的最佳解决方案
补充资料
图像请求的回调可用于截击,您可以使用以下代码
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);
ImageView iv=null/*为ImageView附加指针*/
RequestQueue requestAdministrator=null/*将指针连在一起截击*/
ImageRequest ir=newImageRequest(url,new Response.Listener()){
@凌驾
公共void onResponse(位图响应){
//回拨
iv.设置图像位图(响应);
}
},100,100,空,空);
//100是下载图像之前的自定义尺寸。
requestAdministrator.add(ir);
文档中介绍了这一点:ImageRequest已被弃用,因此我将按如下方式进行操作:
第1步:首先制作应用程序
public class YourApplicationClass extends Application {
private static YourApplicationClass sInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
public static YourApplicationClass getInstance(){
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
mRequestQueue = Volley.newRequestQueue(this);
mImageLoader = new ImageLoader(this.mRequestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(10);
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
});
}
public RequestQueue getRequestQueue(){
return mRequestQueue;
}
public ImageLoader getImageLoader(){
return mImageLoader;
}
}
我有一个更简单的解决方案,用于显示url中的图像并将其存储在缓存中。在不添加其他类的情况下,只有MainActivity。 也许它会帮助某人 这是我的XML,它只显示ImageView
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.natalie.volley.MainActivity">
<ImageView
android:id="@+id/ivImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="50dp"/>
</android.support.constraint.ConstraintLayout>
下面是我的mainavity.java:
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
public class MainActivity extends AppCompatActivity {
private String url = "http://kingofwallpapers.com/picture/picture-010.jpg";
ImageView ivImageView;
RequestQueue mRequestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivImageView = (ImageView)findViewById(R.id.ivImageView);
mRequestQueue = Volley.newRequestQueue(this.getApplicationContext());
ImageRequest imageRequest = new ImageRequest(url, new BitmapListener(), 0, 0, null, null, new MyErrorListener());
mRequestQueue.add(imageRequest);
}
private class BitmapListener implements Response.Listener<Bitmap> {
@Override
public void onResponse(Bitmap response) {
// response = your url's bitmap
ivImageView.setImageBitmap(response);
}
}
private class MyErrorListener implements Response.ErrorListener {
@Override
public void onErrorResponse(VolleyError error) {
//store a default image if connection failed
ivImageView.setImageResource(R.drawable.error_icon);
}
}
}
导入android.graphics.Bitmap;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.widget.ImageView;
导入com.android.volley.RequestQueue;
导入com.android.volley.Response;
导入com.android.volley.VolleyError;
导入com.android.volley.toolbox.ImageRequest;
导入com.android.volley.toolbox.volley;
公共类MainActivity扩展了AppCompatActivity{
专用字符串url=”http://kingofwallpapers.com/picture/picture-010.jpg";
图像视图;
请求队列mRequestQueue;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivImageView=(ImageView)findViewById(R.id.ivImageView);
mRequestQueue=Volley.newRequestQueue(this.getApplicationContext());
ImageRequest ImageRequest=new ImageRequest(url,new BitmapListener(),0,0,null,null,new MyErrorListener());
mRequestQueue.add(imageRequest);
}
私有类BitmapListener实现Response.Listener{
@凌驾
公共void onResponse(位图响应){
//response=url的位图
ivImageView.setImageBitmap(响应);
}
}
私有类MyErrorListener实现Response.ErrorListener{
@凌驾
公共无效onErrorResponse(截击错误){
//如果连接失败,请存储默认映像
我
YourApplicationClass.getInstance().getImageLoader().get(image_url, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
Bitmap bitmap = imageContainer.getBitmap();
//use bitmap
}
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.natalie.volley.MainActivity">
<ImageView
android:id="@+id/ivImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="50dp"/>
</android.support.constraint.ConstraintLayout>
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
public class MainActivity extends AppCompatActivity {
private String url = "http://kingofwallpapers.com/picture/picture-010.jpg";
ImageView ivImageView;
RequestQueue mRequestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivImageView = (ImageView)findViewById(R.id.ivImageView);
mRequestQueue = Volley.newRequestQueue(this.getApplicationContext());
ImageRequest imageRequest = new ImageRequest(url, new BitmapListener(), 0, 0, null, null, new MyErrorListener());
mRequestQueue.add(imageRequest);
}
private class BitmapListener implements Response.Listener<Bitmap> {
@Override
public void onResponse(Bitmap response) {
// response = your url's bitmap
ivImageView.setImageBitmap(response);
}
}
private class MyErrorListener implements Response.ErrorListener {
@Override
public void onErrorResponse(VolleyError error) {
//store a default image if connection failed
ivImageView.setImageResource(R.drawable.error_icon);
}
}
}