2013-08-28 6 views
0

Я пытаюсь кэшировать загруженные растровые изображения с помощью кода Google, но он не работает для меня.Кэширование растровых изображений не работает

загрузить код из этой статьи: http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

И использовал его в моем коде, я не мог найти хороший пример использования, так что я предполагаю, что я не могу использовать его правильно.

В моей OnCreate у меня есть эта строка:

init(new ImageCacheParams(this, this.getApplicationContext().getCacheDir().getPath())); 

Методы инициализации:

private void init(ImageCacheParams cacheParams) { 
         mCacheParams = cacheParams; 

         // Set up memory cache 
         if (mCacheParams.memoryCacheEnabled) { 
          if (BuildConfig.DEBUG) { 
           Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")"); 
          } 

          // If we're running on Honeycomb or newer, then 
          if (Utils.hasHoneycomb()) { 
           mReusableBitmaps = new HashSet<SoftReference<Bitmap>>(); 
          } 

          mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) { 

           /** 
           * Notify the removed entry that is no longer being cached 
           */ 
           @Override 
           protected void entryRemoved(boolean evicted, String key, 
             BitmapDrawable oldValue, BitmapDrawable newValue) { 
            if (RecyclingBitmapDrawable.class.isInstance(oldValue)) { 
             // The removed entry is a recycling drawable, so notify it 
             // that it has been removed from the memory cache 
             ((RecyclingBitmapDrawable) oldValue).setIsCached(false); 
            } else { 
             // The removed entry is a standard BitmapDrawable 

             if (Utils.hasHoneycomb()) { 
              // We're running on Honeycomb or later, so add the bitmap 
              // to a SoftRefrence set for possible use with inBitmap later 
              mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap())); 
             } 
            } 
           } 

           /** 
           * Measure item size in kilobytes rather than units which is more practical 
           * for a bitmap cache 
           */ 
           @Override 
           protected int sizeOf(String key, BitmapDrawable value) { 
            final int bitmapSize = getBitmapSize(value)/1024; 
            return bitmapSize == 0 ? 1 : bitmapSize; 
           } 
          }; 
         } 

         // By default the disk cache is not initialized here as it should be initialized 
         // on a separate thread due to disk access. 
         if (cacheParams.initDiskCacheOnCreate) { 
          // Set up disk cache 
          new InitializesCache().execute(); 
         } 
        } 

class InitializesCache extends AsyncTask<String, Void, Void> 
       { 

        protected Void doInBackground(String... args) { 
         initDiskCache(); 
         return null; 
        } 


public void initDiskCache() { 
        // Set up disk cache 
        synchronized (mDiskCacheLock) { 
         if (mDiskLruCache == null || mDiskLruCache.isClosed()) { 
          File diskCacheDir = mCacheParams.diskCacheDir; 
          if (mCacheParams.diskCacheEnabled && diskCacheDir != null) { 
           if (!diskCacheDir.exists()) { 
            diskCacheDir.mkdirs(); 
           } 
           if (getUsableSpace(diskCacheDir) > mCacheParams.diskCacheSize) { 
            try { 
             mDiskLruCache = DiskLruCache.open(
               diskCacheDir, 1, 1, mCacheParams.diskCacheSize); 
             if (BuildConfig.DEBUG) { 
              Log.d(TAG, "Disk cache initialized"); 
             } 
            } catch (final IOException e) { 
             mCacheParams.diskCacheDir = null; 
             Log.e(TAG, "initDiskCache - " + e); 
            } 
           } 
          } 
         } 
         mDiskCacheStarting = false; 
         mDiskCacheLock.notifyAll(); 
        } 
       } 

Теперь я использую эту строку, когда я загрузить мой растровое изображение из моей БД:

addBitmapToCache("foo", *some drawable*); 

Метод:

public void addBitmapToCache(String data, BitmapDrawable value) { 
        if (data == null || value == null) { 
         return; 
        } 

        // Add to memory cache 
        if (mMemoryCache != null) { 
         if (RecyclingBitmapDrawable.class.isInstance(value)) { 
          // The removed entry is a recycling drawable, so notify it 
          // that it has been added into the memory cache 
          ((RecyclingBitmapDrawable) value).setIsCached(true); 
         } 
         mMemoryCache.put(data, value); 
        } 

        synchronized (mDiskCacheLock) { 
         // Add to disk cache 
         if (mDiskLruCache != null) { 
          final String key = hashKeyForDisk(data); 
          OutputStream out = null; 
          try { 
           DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key); 
           if (snapshot == null) { 
            final DiskLruCache.Editor editor = mDiskLruCache.edit(key); 
            if (editor != null) { 
             out = editor.newOutputStream(DISK_CACHE_INDEX); 
             value.getBitmap().compress(
               mCacheParams.compressFormat, mCacheParams.compressQuality, out); 
             editor.commit(); 
             out.close(); 
            } 
           } else { 
            snapshot.getInputStream(DISK_CACHE_INDEX).close(); 
           } 
          } catch (final IOException e) { 
           Log.e(TAG, "addBitmapToCache - " + e); 
          } catch (Exception e) { 
           Log.e(TAG, "addBitmapToCache - " + e); 
          } finally { 
           try { 
            if (out != null) { 
             out.close(); 
            } 
           } catch (IOException e) {} 
          } 
         } 
        } 
       } 

После того, что я пытаюсь получить растровое изображение, вызвав этим:

tempImage.setImageDrawable(getBitmapFromMemCache("foo")); 

public BitmapDrawable getBitmapFromMemCache(String data) { 
        BitmapDrawable memValue = null; 

        if (mMemoryCache != null) { 
         memValue = mMemoryCache.get(data); 
        } 

        if (BuildConfig.DEBUG && memValue != null) { 
         Log.d(TAG, "Memory cache hit"); 
        } 

        return memValue; 
       } 

При использовании этого потока я не вижу мои растровый я не получаю никаких ошибок.

Я также попытался посмотреть другие коды git для кеша, но все коды на самом деле непонятно, как использовать, с отсутствием примера или вообще никакого описания.

ответ