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:org.tigase.mobile.utils.AvatarHelper.java

public static void initilize(Context context_) {
    if (avatarCache == null) {
        context = context_;//from w  ww .  j av a 2s  . c  o  m

        density = context.getResources().getDisplayMetrics().density;
        defaultAvatarSize = Math.round(density * 50);

        // Get memory class of this device, exceeding this amount will throw
        // an
        // OutOfMemory exception.
        final int memClass = ((android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
                .getMemoryClass();

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = 1024 * 1024 * memClass / 8;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            avatarCache = new LruCache<BareJID, Bitmap>(cacheSize) {
                @TargetApi(12)
                @Override
                protected int sizeOf(BareJID key, Bitmap bitmap) {
                    // The cache size will be measured in bytes rather than
                    // number of items. Ignoring placeholder bitmap as well.
                    return bitmap == mPlaceHolderBitmap ? 0 : bitmap.getByteCount();
                }
            };
        } else {
            // below SDK 12 there is no getByteCount method
            avatarCache = new LruCache<BareJID, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(BareJID key, Bitmap bitmap) {
                    // The cache size will be measured in bytes rather than
                    // number of items. Ignoring placeholder bitmap as well.
                    return bitmap == mPlaceHolderBitmap ? 0 : (bitmap.getRowBytes() * bitmap.getHeight());
                }
            };
        }

        mPlaceHolderBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.user_avatar);
    }
}

From source file:com.vinay.volley.lazyload.BitmapCache.java

/**
 * Initialize the cache.//  w w w .j  a v a  2 s . c o m
 */
private void init(int memCacheSize) {
    // Set up memory cache
    Log.d(TAG, "Memory cache created (size = " + memCacheSize + "KB)");
    mMemoryCache = new LruCache<String, Bitmap>(memCacheSize) {
        /**
         * Measure item size in kilobytes rather than units which is more practical for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            final int bitmapSize = getBitmapSize(bitmap) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }
    };
}

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

/**
 * Initialize the cache.//from  w w w.j  a v a 2s.c  o m
 */
private void init(int memCacheSize) {
    // Set up memory cache
    VolleyLog.d(TAG, "Memory cache created (size = " + memCacheSize + "KB)");
    mMemoryCache = new LruCache<String, Bitmap>(memCacheSize) {
        /**
         * Measure item size in kilobytes rather than units which is more practical
         * for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            final int bitmapSize = getBitmapSize(bitmap) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }
    };
}

From source file:com.ncode.android.apps.schedo.util.BitmapCache.java

/**
 * Initialize the cache.//  www  . ja  v a2s .  c  om
 */
private void init(int memCacheSize) {
    // Set up memory cache
    LogUtils.LOGD(TAG, "Memory cache created (size = " + memCacheSize + "KB)");
    mMemoryCache = new LruCache<String, Bitmap>(memCacheSize) {
        /**
         * Measure item size in kilobytes rather than units which is more practical
         * for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            final int bitmapSize = getBitmapSize(bitmap) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }
    };
}

From source file:li.zeitgeist.android.worker.ThumbnailWorker.java

/**
 * Constructs the thumbnail loader./*from   w  w  w. jav  a  2  s.  c  om*/
 *
 * This starts the thread pool, initializes the memory cache,
 * and creates the directories for the disk-cache (if necessary).
 * 
 * @param context of the gallery service.
 */
public ThumbnailWorker(Context context) {
    Log.v(TAG, "constructed");

    api = ZeitgeistApiFactory.createInstance(context);

    // start thread pool
    pool = Executors.newFixedThreadPool(THREADS);

    // initialize memory cache
    /*
            
     TODO: somehow that doesn't work at all, why?
            
    int memCacheSize = 2 * 1024 * 1024; // 2 MiB
    memCache = new LruCache<Integer, Bitmap>(memCacheSize) {
        protected int sizeOf(Integer key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };
            
    */
    // 150 * ~16 KiB = 2250 KiB
    memCache = new LruCache<Integer, Bitmap>(150);

    // create disk cache directory
    File externalStorageDirectory = context.getExternalFilesDir(null);
    diskCache = new File(externalStorageDirectory, "cache");
    if (!diskCache.exists()) {
        diskCache.mkdirs();
    }
    Log.d(TAG, "disk cache: " + diskCache.getAbsolutePath());

    // load video overlay bitmap
    videoOverlayBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.video_overlay);
}

From source file:com.social.solution.fragment.MyImageFragment.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;/*from  www .j a v a  2  s . co 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.bluepixel.android.sgpool.util.BitmapCache.java

/**
 * Initialize the cache.//from  w w w . j  a v a 2  s . c om
 */
private void init(int memCacheSize) {
    // Set up memory cache
    LOGD(TAG, "Memory cache created (size = " + memCacheSize + "KB)");
    mMemoryCache = new LruCache<String, Bitmap>(memCacheSize) {
        /**
         * Measure item size in kilobytes rather than units which is more practical
         * for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            final int bitmapSize = getBitmapSize(bitmap) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }
    };
}

From source file:ch.carteggio.ui.ConversationIconLoader.java

/**
 * Constructor./*  www  . j  a v a 2s  .co m*/
 *
 * @param context
 *         A {@link Context} instance.
 * @param defaultBackgroundColor
 *         The ARGB value to be used as background color for the fallback picture. {@code 0} to
 *         use a dynamically calculated background color.
 */
public ConversationIconLoader(Context context, int defaultBackgroundColor) {
    Context appContext = context.getApplicationContext();
    mContentResolver = appContext.getContentResolver();
    mResources = appContext.getResources();
    mHelper = new CarteggioProviderHelper(appContext);

    float scale = mResources.getDisplayMetrics().density;
    mPictureSizeInPx = (int) (PICTURE_SIZE * scale);

    mDefaultBackgroundColor = defaultBackgroundColor;

    ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
    int memClass = activityManager.getMemoryClass();

    // Use 1/16th of the available memory for this memory cache.
    final int cacheSize = 1024 * 1024 * memClass / 16;

    mBitmapCache = new LruCache<Long, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(Long key, Bitmap bitmap) {
            // The cache size will be measured in bytes rather than number of items.
            return bitmap.getByteCount();
        }
    };
}

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

public ImageLoader(Context context) {
    this.context = context;
    handler = new Handler(Looper.getMainLooper());
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    cacheSize = maxMemory / 4;//w ww  .  ja v  a2 s . com

    // 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
        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 && oldBitmap != nowPlayingSmall) || clearingCache) {
                    oldBitmap.recycle();
                } else if (oldBitmap != newBitmap) {
                    cache.put(key, oldBitmap);
                }
            }
        }
    };
}

From source file:com.foxykeep.datadroid.requestmanager.RequestManager.java

protected RequestManager(Context context, Class<? extends RequestService> requestService) {
    mContext = context.getApplicationContext();

    mRequestService = requestService;/*  www .jav  a2  s .  c  om*/
    mRequestReceiverMap = new HashMap<Request, RequestReceiver>();
    mMemoryCache = new LruCache<Request, Bundle>(30);
}