我为我当前的应用程序使用自定义列表视图,除了图像缓存外,一切都很好。图像不是缓存。任何人请帮我在我的代码中找到我的错误。
这是我的代码:
DownloadImage中的参数URL是完整的图片网址。
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
/*Write to Cache*/
String[] imageName = URL.split("/");
String imageFile = imageName[imageName.length-1];
File file = new File(context.getCacheDir(), imageFile);
file.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100 , bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
bos.close();
/*Write to Cache*/
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
bitmap = null;
}
return bitmap;
}
代码OpenHttpConnection:
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}