Кэширование растровых изображений не работает

Я пытаюсь кэшировать загруженные растровые изображения с помощью кода 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 для кэширования, но все коды действительно неясны, как их использовать, с отсутствием примеров или вообще без описания.


person dasdasd    schedule 28.08.2013    source источник


Ответы (1)


Используйте библиотеку Android Universal Image Loader для загрузки и кэширования растровых изображений.

person danik    schedule 28.08.2013