我的程序有一个问题,就是在添加了LruCache后就不显示图片了
package com.example.imoc.Adapter;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
@SuppressLint("NewApi")
public class HttpAsyncTask {
// 缓存
private LruCache<String, Bitmap> mCache;
public HttpAsyncTask() {
int maxMeory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMeory / 4;
mCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
}
public void addBitmap2Cache(String url, Bitmap bitmap) {
if (getBitmap4Cache(url) == null) {
mCache.put(url, bitmap);
}
}
public Bitmap getBitmap4Cache(String url) {
return mCache.get(url);
}
public void showImageByAsync(ImageView imageView, String url) {
Bitmap bitmap = getBitmap4Cache(url);
if (bitmap == null) {
new NewsAsyncTask(imageView, url).execute(url);
} else {
imageView.setImageBitmap(bitmap);
}
// new NewsAsyncTask(imageView,url).execute(url);
}
public Bitmap getBitmapFromUrl(String sturl) {
Bitmap bitmap = null;
InputStream inputStream = null;
try {
URL url = new URL(sturl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
inputStream = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(inputStream);
connection.connect();
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
private class NewsAsyncTask extends AsyncTask<String, Void, Bitmap> {
private ImageView mimageView;
private String mUrl;
public NewsAsyncTask(ImageView imageView, String url) {
mimageView = imageView;
mUrl = url;
}
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String url = params[0];
Bitmap bitmap = getBitmap4Cache(url);
if (bitmap != null) {
addBitmap2Cache(url, bitmap);
}
return bitmap;
// return getBitmapFromUrl(params[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (mimageView.getTag().equals(mUrl)) {
mimageView.setImageBitmap(result);
}
}
}
}
adapter 中也设置了