如何将这个cacheBitmap方法与这个图像的getter代码集成?

时间:2011-07-28 16:20:52

标签: android

我将如何整合此缓存方法..

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);    
    }

使用此代码......

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);
    }

编辑:给我一个语法错误

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:另一种语法错误

Cannot instantiate the type Uri

  Uri imageUri = new Uri(aURL);

1 个答案:

答案 0 :(得分:1)

在调用aURL.openConnection()之前,您需要检查url是否在磁盘缓存中;如果是,你可以从那里阅读,而不是继续从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

检索到位图后,您希望将其缓存到磁盘:

                            bis.close();
                            is.close();
                            Log.v(imageUrl, "Retrieving image");
                            putBitmapInDiskCache(imageUri, bm);