如何将400kb大小的位图存储到android中的LRUCache中

时间:2013-09-27 09:50:14

标签: android bitmap android-image android-lru-cache

在列表视图上点击项目我从SD卡获取图像,我将存储到LRUCache中。 图像尺寸为400kb,750 * 580。但是从缓存中检索位图时,位图为空。

这是我的代码: 这里lv是listview,showpicture是第一次从sdcard获取位图的方法。

    private LruCache<String, Bitmap> mMemoryCache;
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            int memClassBytes = am.getMemoryClass() * 1024 * 1024;
            int cacheSize = memClassBytes / 8;

     mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    // The cache size will be measured in kilobytes rather than
                    // number of items.
                    return bitmap.getRowBytes() * bitmap.getHeight();

                }
            };


    lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                if (!items.get(position).isSection()) {


                    EntryItem item = (EntryItem)items.get(position);

                    synchronized(mMemoryCache) {
                        lBitmap = mMemoryCache.get(item.getHallID());

                        if(lBitmap!=null){
                        vss.setImageBitmap(lBitmap);
                        Log.d("From cache", "from cache");
                        }
                    }

                    if(mMemoryCache.get(item.getHallID())==null){


                     hallimg = showPicture(Environment.getExternalStorageDirectory()
                    .getAbsolutePath()
                    + "/MLPA_VENUE/"
                    + item.getVenuename(), item.getSeatPlanImg(),item.getHallID());
                     Log.d("From not cache", "from not cache");
                     vss.setImageBitmap(hallimg);


                    }

///Below method to get bitmap from sdcard and to store in cache.

    public Bitmap showPicture(String path, String fileName,String hallID) {
        File f = new File(path, fileName);
        FileInputStream is = null;
        try {
            is = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            Log.d("error: ", String.format(
                    "ShowPicture.java file[%s]Not Found", fileName));
            return null;
        }

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inMutable = true;
        opt.inPurgeable=true;
        opt.inInputShareable=true;
        opt.inDither=true;
        opt.inTempStorage=new byte[32*1024];
        if(bm!=null){
            bm.recycle();
        }
         bm = BitmapFactory.decodeStream(is, null, opt);
        synchronized (mMemoryCache) {

            mMemoryCache.put(hallID, bm);
           }
        return bm;
    }

0 个答案:

没有答案