How would i go about integrating this cache method..
public void putBitmapInDiskCache(Uri url, Bitmap avatar) {
File cacheDir = new File(this.getCacheDir(), "thumbnails");
File cacheFile = new File(cacheDir, ""+url.hashCode());
try {
cacheFile.createNewFile();
FileOutputStream fos = new FileOutputStream(cacheFile);
avatar.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("error", "Error when saving image to cache. ", e);
}
With this code....
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
try {
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.setUseCaches(true);
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
Log.v(imageUrl, "Retrieving image");
/* Apply the Bitmap to the ImageView that will be returned. */
i.setImageBitmap(bm);
}
EDIT: Gives me a syntax error
The constructor File(File, int) is undefined
Uri imageUri = new Uri(aURL);
File cachePath = new File(new File(myContext.getCacheDir(), "thumbnails"), imageUri.hashCode()).exists();
if (new File(new File(myContext.getCacheDir(), "thumbnails"), imageUri.hashCode()).exists())
开发者_运维知识库 {
} else {
EDIT2: Another syntax error
Cannot instantiate the type Uri
Uri imageUri = new Uri(aURL);
Before you call aURL.openConnection(), you want to check if the url is in the disk cache; if it is you can read it from there instead of proceeding with reading it from the URL.
URL aURL = new URL(myRemoteImages[position]);
Uri imageUri = new Uri(aURL);
if (new File(new File(this.getCacheDir(), "thumbnails"), "" + imageUri.hashCode()).exists())
{
...read from cache
} else {
... rest of read from URL code
After you've retrieved the bitmap, you want to cache it to disk:
bis.close();
is.close();
Log.v(imageUrl, "Retrieving image");
putBitmapInDiskCache(imageUri, bm);
精彩评论