1

在单击列表视图上的项目时,我从 sdcard 获取图像并将其存储到 LRUCache 中。图片大小为 400kb,尺寸为 750*580。但是在从缓存中检索位图时,位图为空。

这是我的代码:这里 lv 是列表视图,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;
    }
4

0 回答 0