Example usage for android.support.v4.util LruCache LruCache

List of usage examples for android.support.v4.util LruCache LruCache

Introduction

In this page you can find the example usage for android.support.v4.util LruCache LruCache.

Prototype

public LruCache(int maxSize) 

Source Link

Usage

From source file:github.madmarty.madsonic.util.ImageLoader.java

public ImageLoader(Context context) {

    this.context = context;

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 4;

    cache = new LruCache<String, Bitmap>(cacheSize) {
        @Override/* ww  w.jav  a  2 s.  c om*/
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, Bitmap oldBitmap, Bitmap newBitmap) {
            if (evicted) {
                try {
                    oldBitmap.recycle();
                } catch (Exception e) {
                    // Do nothing, just means that the drawable is a flat image
                }
            }
        }
    };

    queue = new LinkedBlockingQueue<Task>(1000);

    // Determine the density-dependent image sizes.
    imageSizeDefault = (int) Math
            .round((context.getResources().getDrawable(R.drawable.unknown_album).getIntrinsicHeight()));
    LOG.info("imageSizeDefault: " + imageSizeDefault);

    imageSizeMedium = 180; // (int) Math.round((context.getResources().getDrawable(R.drawable.unknown_album_medium).getIntrinsicHeight()));;
    LOG.info("imageSizeMedium: " + imageSizeMedium);

    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    imageSizeLarge = (int) Math.round(Math.min(metrics.widthPixels, metrics.heightPixels) * 0.6);
    LOG.info("imageSizeLarge: " + imageSizeLarge);

    //        imageSizeDefault = Util.getCoverSize(context);

    for (int i = 0; i < CONCURRENCY; i++) {
        new Thread(this, "ImageLoader").start();
    }

    createLargeUnknownImage(context);
}

From source file:com.android.volley.plus.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///  w  ww  .ja  v  a2  s . c  om
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 + ")");
        //            }
        mMemoryCache = new LruCache<String, Bitmap>(mCacheParams.memCacheSize) {
            /**
             * Measure item size in bytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return getBitmapSize(bitmap);
            }
        };
    }

    // 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
        initDiskCache();
    }
}

From source file:com.tony.mushrommstreet.waterfall.ImageCache.java

private void init(Context context, ImageCacheParams cacheParams) {
    final File diskCacheDir = DiskLruCache.getDiskCacheDir(context, cacheParams.uniqueName);

    // Set up disk cache
    if (cacheParams.diskCacheEnabled) {
        mDiskCache = DiskLruCache.openCache(context, diskCacheDir, cacheParams.diskCacheSize);
        mDiskCache.setCompressParams(cacheParams.compressFormat, cacheParams.compressQuality);
        if (cacheParams.clearDiskCacheOnStart) {
            mDiskCache.clearCache();/*from  w  w w . j  av a 2  s .co  m*/
        }
    }

    // Set up memory cache
    if (cacheParams.memoryCacheEnabled) {
        mMemoryCache = new LruCache<String, Bitmap>(cacheParams.memCacheSize) {
            /**
             * Measure item size in bytes rather than units which is more practical for a bitmap
             * cache
             */
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return Utils.getBitmapSize(bitmap);
            }
        };
    }
}

From source file:github.daneren2005.dsub.util.ImageLoader.java

public ImageLoader(Context context) {
    this.context = context;
    handler = new Handler(Looper.getMainLooper());
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 4;

    // Determine the density-dependent image sizes.
    imageSizeDefault = context.getResources().getDrawable(R.drawable.unknown_album).getIntrinsicHeight();
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    imageSizeLarge = Math.round(Math.min(metrics.widthPixels, metrics.heightPixels));
    avatarSizeDefault = context.getResources().getDrawable(R.drawable.ic_social_person).getIntrinsicHeight();

    cache = new LruCache<String, Bitmap>(cacheSize) {
        @Override/*w  w  w .j  av  a 2  s .c o  m*/
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, Bitmap oldBitmap, Bitmap newBitmap) {
            if (evicted) {
                if (oldBitmap != nowPlaying || clearingCache) {
                    oldBitmap.recycle();
                } else {
                    cache.put(key, oldBitmap);
                }
            }
        }
    };
}

From source file:com.social.solution.unused.AddSegment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //View view  = inflater.inflate(R.layout.image_list, container, false);
    View view = inflater.inflate(R.layout.image_list, container, false);

    mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
    mSwipeLayout.setProgressViewOffset(false, 150, 200);

    storedView = view;// w w w.  j ava  2s.c o m

    parentActivity = getActivity();
    mInflater = LayoutInflater.from(parentActivity);

    //imageUrls = TweetBank.getAllImageUrls();
    //imageTweets =  TweetBank.getAllNewsTweets();

    mRequestQueue = Volley.newRequestQueue(parentActivity);
    mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
        private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(10);

        public void putBitmap(String url, Bitmap bitmap) {
            mCache.put(url, bitmap);
        }

        public Bitmap getBitmap(String url) {
            return mCache.get(url);
        }
    });

    listView = (ObservableListView) view.findViewById(R.id.mylist);

    if (parentActivity instanceof ObservableScrollViewCallbacks) {
        // Scroll to the specified position after layout
        Bundle args = getArguments();
        if (args != null && args.containsKey(ARG_INITIAL_POSITION)) {
            final int initialPosition = args.getInt(ARG_INITIAL_POSITION, 0);
            ScrollUtils.addOnGlobalLayoutListener(listView, new Runnable() {
                @Override
                public void run() {
                    // scrollTo() doesn't work, should use setSelection()
                    listView.setSelection(initialPosition);
                }
            });
        }

        // TouchInterceptionViewGroup should be a parent view other than ViewPager.
        // This is a workaround for the issue #117:
        // https://github.com/ksoichiro/Android-ObservableScrollView/issues/117
        listView.setTouchInterceptionViewGroup((ViewGroup) parentActivity.findViewById(R.id.root));
        listView.setScrollViewCallbacks((ObservableScrollViewCallbacks) parentActivity);
    }

    View newsrowslist = (View) inflater.inflate(R.layout.newsrowslistlayout, listView, false);

    newsrowslist.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            System.out.println("pranjal danger");
            return false;
        }
    });

    //imageAdapter              = new ImageAdapter(parentActivity);
    //imageAdapterHorizontal    = new ImageAdapterHorizontal(parentActivity);

    setmydata(listView, inflater.inflate(R.layout.padding, listView, false));

    //listView.setAdapter(imageAdapterHorizontal);

    listView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //System.out.println("hello pranjal how are you");
            return false;
        }
    });

    /*
    View horizontalView  = null;
    ViewGroup imageviews = null;
    int count            = 0;
            
    for (Tweet t : imageTweets) {
    if(count == 0) {
        //horizontalView = inflater.inflate(R.layout.myhorizontalscrollviewa, null);//, true);
        horizontalView = inflater.inflate(R.layout.myhorizontalscrollviewa, container, false);
        TextView    tv = new TextView(parentActivity);
        tv.setText("POLITICS");
        newsrowslist.addView(tv);
        newsrowslist.addView(horizontalView);
        imageviews     = (ViewGroup) horizontalView.findViewById(R.id.imageviews);
    }
            
    ++count;
    count = count%5;
            
    //final View v = mInflater.inflate(R.layout.new_grid_item, null);
    final View v = mInflater.inflate(R.layout.new_grid_item, container, false);
    final SquareImageView picture = (SquareImageView) v.findViewById(R.id.picture);
    final TextView name = (TextView) v.findViewById(R.id.picturetext);
            
    name.setTag(0);
    name.setTag(R.id.action0, name.getTop());
            
    name.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int flag = (int) v.getTag();
            Layout t = name.getLayout();
            
            int left = name.getLeft();
            int right = name.getRight();
            int bottom = name.getBottom();
            
            if (flag == 0) {
                //name.setMaxLines(5);
                System.out.println("pranjal LAYOUT 0 width = " + t.getWidth() + " height " + t.getHeight());
                int top = 0;
                // l t r b
                name.layout(left, top, right, picture.getBottom());
                name.setBackgroundColor(Color.parseColor("#FF000000"));
                name.setGravity(Gravity.NO_GRAVITY);
                name.setTag(1);
            } else {
                //name.setMaxLines(2);
                System.out.println("pranjal LAYOUT 1 width = " + t.getWidth() + " height " + t.getHeight());
                int top = (int) name.getTag(R.id.action0);
            
                System.out.println("new top position is " + top);
            
                // l t r b
                name.layout(left, picture.getBottom() - 40, right, picture.getBottom());
                name.setGravity(Gravity.NO_GRAVITY);
                name.setTag(0);
            }
            return false;
        }
    });
            
    picture.setImageUrl(t.entities.media.get(0).mediaUrl, mImageLoader);
    String temp  = t.text;
    temp = temp+"\n";
    String temp1 = temp.replaceAll("http.*?\\s", " ").replaceAll("http.*?\\n", "");
    System.out.println("STRING1 "+temp+ " STRING2 "+temp1);
    name.setText(Html.fromHtml("<b>@" + t.user.screenName + "</b><br>" + temp1));
    imageviews.addView(v);
    }*/
    return view;
}

From source file:com.android.volley.cache.MemLruImageCache.java

/**
 * Initialize the cache.// ww w  .  jav  a  2s .c  o m
 */
private void init(int memCacheSize) {
    // Set up memory cache
    VolleyLog.d(TAG, "Memory cache created (size = " + memCacheSize + "KB)");
    // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
    // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
    // of SoftReferences which will actually not be very effective due to the garbage
    // collector being aggressive clearing Soft/WeakReferences. A better approach
    // would be to use a strongly references bitmaps, however this would require some
    // balancing of memory usage between this set and the bitmap LruCache. It would also
    // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
    // the size would need to be precise, from KitKat onward the size would just need to
    // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
    //        if (Utils.hasHoneycomb()) {
    //            mReusableBitmaps =
    //                    Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
    //        }
    mMemoryCache = new LruCache<String, BitmapDrawable>(memCacheSize) {
        /**
         * Measure item size in kilobytes rather than units which is more practical
         * for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, BitmapDrawable bitmap) {
            final int bitmapSize = getBitmapSize(bitmap) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                BitmapDrawable newValue) {
            super.entryRemoved(evicted, key, oldValue, newValue);

            VolleyLog.d(TAG, "Memory cache entry removed - " + key);
            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 if(oldValue != null && mReusableMemoryCache!=null && Utils.hasHoneycomb())//mReusableMemoryCache only hasHoneycomb need
              {
               mReusableMemoryCache.put(key, new SoftReference<BitmapDrawable>(oldValue));
              }*/
        }
    };

    //        mReusableMemoryCache = new LruCache<String, SoftReference<BitmapDrawable>>(memCacheSize) {
    //            /**
    //             * Measure item size in kilobytes rather than units which is more practical
    //             * for a bitmap cache
    //             */
    //            @Override
    //            protected int sizeOf(String key, SoftReference<BitmapDrawable> bitmapRef) {
    //                final int bitmapSize = getBitmapSize(bitmapRef.get()) / 1024;
    //                return bitmapSize == 0 ? 1 : bitmapSize;
    //            }
    //
    //            @Override
    //            protected void entryRemoved(boolean evicted, String key, SoftReference<BitmapDrawable> oldValue, SoftReference<BitmapDrawable> newValue) {
    //               super.entryRemoved(evicted, key, oldValue, newValue);
    //
    //               VolleyLog.d(TAG, "Memory cache entry removed - " + key);
    //              // The removed entry is a standard BitmapDrawable
    //
    //             /* if (Utils.hasHoneycomb()) {
    //                  // We're running on Honeycomb or later, so add the bitmap
    //                  // to a SoftReference set for possible use with inBitmap later
    //                  mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.get().getBitmap()));
    //              }*/
    //            }
    //        };
}

From source file:ollie.Ollie.java

/**
 * Initialize the database. Must be called before interacting with the database.
 *
 * @param context   Context/*from  w w  w  . j av  a 2s  . co m*/
 * @param name      The database name.
 * @param version   The database version.
 * @param cacheSize The cache size.
 * @param logLevel  The logging level.
 */
public static void init(Context context, String name, int version, int cacheSize, LogLevel logLevel) {
    sLogLevel = logLevel;

    if (sInitialized) {
        if (sLogLevel.log(LogLevel.BASIC)) {
            Log.d(TAG, "Already initialized.");
        }
        return;
    }

    try {
        Class adapterClass = Class.forName(AdapterHolder.IMPL_CLASS_FQCN);
        sAdapterHolder = (AdapterHolder) adapterClass.newInstance();
    } catch (Exception e) {
        if (sLogLevel.log(LogLevel.BASIC)) {
            Log.e(TAG, "Failed to initialize.", e);
        }
    }

    sContext = context.getApplicationContext();
    sDatabaseHelper = new DatabaseHelper(sContext, name, version);
    sSQLiteDatabase = sDatabaseHelper.getWritableDatabase();
    sCache = new LruCache<String, Model>(cacheSize);

    sInitialized = true;
}

From source file:com.seun.gallery.util.ImageCache.java

/**
 * Initialize the cache/*from ww  w  .ja v  a2s .  com*/
 */
private void init(int memoryCacheSize) {
    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (DEBUG) {
        Log.d(TAG, "Memory cache created (size = " + memoryCacheSize + ")");
    }

    // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
    // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
    // of SoftReferences which will actually not be very effective due to the garbage
    // collector being aggressive clearing Soft/WeakReferences. A better approach
    // would be to use a strongly references bitmaps, however this would require some
    // balancing of memory usage between this set and the bitmap LruCache. It would also
    // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
    // the size would need to be precise, from KitKat onward the size would just need to
    // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
    }

    mMemoryCache = new LruCache<String, BitmapDrawable>(memoryCacheSize) {

        /**
         * 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 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    // We're running on Honeycomb or later, so add the bitmap
                    // to a SoftReference 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;
        }
    };
    //END_INCLUDE(init_memory_cache)
}

From source file:org.chromium.chrome.browser.download.ui.ThumbnailProviderImpl.java

private static LruCache<String, Bitmap> getBitmapCache() {
    ThreadUtils.assertOnUiThread();//ww  w.j ava  2s  .  co m

    LruCache<String, Bitmap> cache = sBitmapCache == null ? null : sBitmapCache.get();
    if (cache != null)
        return cache;

    // Create a new weakly-referenced cache.
    cache = new LruCache<String, Bitmap>(MAX_CACHE_BYTES) {
        @Override
        protected int sizeOf(String key, Bitmap thumbnail) {
            return thumbnail == null ? 0 : thumbnail.getByteCount();
        }
    };
    sBitmapCache = new WeakReference<>(cache);
    return cache;
}

From source file:com.example.imagedownloader.ImageDownloader.java

public ImageDownloader(Activity actv) {
    imagesDirectory = Storage.getImagesDirectory();
    if (withRetainFragment) {
        RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(actv.getFragmentManager());
        mMemoryCache = RetainFragment.mRetainedCache;
        if (mMemoryCache == null) {
            mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
                @Override/*from  w  w w  .  jav  a  2s .  c o  m*/
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getByteCount() / 1024;
                }

            };
            mRetainFragment.mRetainedCache = mMemoryCache;
        }
    } else {
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount() / 1024;
            }
        };
    }

    File diskCacheDir = Storage.getDiskCacheDirectory(IMG_W, IMG_H);
    Log.d(LOG_TAG, "DISK cache Dir: " + diskCacheDir);
    new InitDiskCacheTask().execute(diskCacheDir);

    //------------------------------------------------------ END OF INIT CACHE
}