如何使用Universal Image Loader清除Android缓存?

18

我正在使用UIL在列表视图中加载图像。

当我长按列表视图中的图像时,我显示一个对话框来修改该图片,并使用相机替换它。

如果我拍摄了一张新图片,则当关闭对话框后,我的列表视图仍然显示旧的图片(因为它被缓存了)。如果我关闭并重新启动应用程序,然后再进入列表视图,新的图片将正确显示。

这是我设置UIL的方式:

// Get singletone instance of ImageLoader
    imageLoader = ImageLoader.getInstance();

    //set display options for image loader
    DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
    .cacheInMemory()
    .displayer(new FadeInBitmapDisplayer(500)) //fade in images
    .resetViewBeforeLoading()
    .build();

    //set image loader options
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).defaultDisplayImageOptions(displayOptions).build();

    // Initialize ImageLoader with configuration.
    imageLoader.init(config);

如果我移除 .cacheInMemory() ,一切都可以正常工作。我只是想知道是否可以在打开对话框时清除缓存。我尝试获取选定的 ImageView 并在打开对话框时调用 myImageView.invalidate(),但没有成功。
这些图片是从文件加载的:
// Load and display image asynchronously
imageLoader.displayImage(file_prefix + image_path, image);

有什么建议吗?

编辑:长按图像时创建上下文菜单的代码,我尝试在那里清除缓存:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    //get info about item selected
    AdapterView.AdapterContextMenuInfo info;
    try {
        // Casts the incoming data object into the type for AdapterView objects.
        info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    } catch (ClassCastException e) {
        // If the menu object can't be cast, logs an error.
        Log.e("no info", "bad menuInfo", e);
        return;
    }
    Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
    if (cursor == null) {
        // For some reason the requested item isn't available, do nothing
        return;
    }

    //remove selected image from cache (if it is an image)
    imageUrl = cursor.getString(cursor.getColumnIndex("image_path"));
    if (!imageUrl.equalsIgnoreCase("")) {
        MemoryCacheUtil.removeFromCache(imageUrl, imageLoader.getMemoryCache());
    }

    Log.i("imageUrl", imageUrl);

    //get defect row ID and text content to pass it to defect activity
    defect_row_id = cursor.getLong(cursor.getColumnIndex("_id"));
    defect_txt = cursor.getString(cursor.getColumnIndex("defect"));

    MenuInflater inflater = getMenuInflater();

    Log.i("cursor", DatabaseUtils.dumpCursorToString(cursor));

    //set project identifier in context menu header, mapping cursor sequence of values
    menu.setHeaderTitle(getString(R.string.select_an_option));
    inflater.inflate(R.menu.menu_defect_row, menu);

}

当选择菜单项(编辑或删除)时

@Override
public boolean onContextItemSelected(MenuItem item) {
    //AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {

    case R.id.edit:

        //open defect activity with the specified image and defect pre-loaded
        Intent editDefectIntent = new Intent(this, DefectActivity.class);

        editDefectIntent.putExtra("defect_row_id", defect_row_id);
        editDefectIntent.putExtra("imageUrl", imageUrl);

        startActivity(editDefectIntent);

        return true;
    case R.id.delete:

        askDeleteConfirm();

        return true;

    default:
        return false;
    }

}//onContextItemSelected

编辑:代码以显示图像列表

@Override
public void onResume() {
    super.onResume();

    //open connection to db
    db = new DBAdapter(this);
    db.open();

    Log.i("DefectListActivity -> onResume", "called");

    // get all defects for this unit
    defectList = db.getAllDefectsByUnit(unit_id);
    // create an array adapter and let it to display our row
    defects = new SimpleCursorAdapter(this, R.layout.defect_row, defectList, new String[] { "defect", "image_path" }, new int[] { R.id.defect, R.id.image }, 0);

    //set custom view using ViewBinder
    SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

            int placeholder_id = getResources().getIdentifier("placeholder", "drawable", getPackageName());

            //get column name
            String name = cursor.getColumnName(columnIndex);

            //for the thumbnail column,if we have an image replace the placeholder
            if ("image_path".equals(name)) {

                ImageView image = (ImageView) view.findViewById(R.id.image);
                //Bitmap thumbnail;
                String image_path = cursor.getString(columnIndex);

                Log.i("image_path ->", image_path);

                if (!image_path.equalsIgnoreCase("")) {

                // Load and display image asynchronously
                imageLoader.displayImage(file_prefix + image_path, image);

                } else {

                    image.setImageResource(placeholder_id);


                    }

                return true;

            }

            //for the defect column, just add the text to the view
            if ("defect".equals(name)) {

                String defect_text = cursor.getString(columnIndex);

                TextView defect_holder = (TextView) view.findViewById(R.id.defect);
                defect_holder.setText(defect_text);

                return true;
            }

            return false;
        }
    };

    defects.setViewBinder(binder);

    setListAdapter(defects);

}//onResume
3个回答

28

如果你同时在内存和磁盘中进行缓存,例如:

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())         
        .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) 
        .discCache(new UnlimitedDiscCache(cacheDir)) 
.........

请确保您从两个位置都将其移除,然后重新加载图像视图。

MemoryCacheUtils.removeFromCache(url, ImageLoader.getInstance().getMemoryCache());
DiscCacheUtils.removeFromCache(url, ImageLoader.getInstance().getDiscCache());

2
我没有找到 DiscCacheUtilsgetDiscCache。我认为你想说的是 DiskCacheUtilsgetDiskCache - Antonio
1
我之前使用的是旧版本的库,现在我正在使用以下代码: ImageLoader.getInstance().getDiscCache() ImageLoader.getInstance().getMemoryCache()而且我相信 DiscCacheUtil 在 1.9.+ 版本中仍然存在。 - Bundeeteddee

20

这应该可以运行:

imageLoader.clearMemoryCache();

7
清除内存缓存的代码为:imageLoader.clearMemoryCache(); 清除磁盘缓存的代码为:imageLoader.clearDiscCache(); - Hannan Shaik

10

我认为在打开对话框时应该删除内存缓存中的缓存图像。使用MemoryCacheUtil来实现:

MemoryCacheUtils.removeFromCache(imageUrl, imageLoader.getMemoryCache());

我尝试过了,但它不起作用。我正在打开一个上下文菜单,然后是一个对话框。我在我的 onCreateContextMenu 中添加了这些行,但它什么也没做。我还尝试将图像 URL 传递给对话框,并从那里获取 imageLoader 单例来清除缓存,但结果仍然相同。 - Paranoid Android
我不理解你的逻辑。请在问题中添加一些代码。 - nostra13
我添加了上下文菜单的代码,在替换图片为新图片之前,我清除选择的图片的缓存。但是它仍然没有起作用... - Paranoid Android
我没有看到你显示图像的地方。 - nostra13
我也有同样的问题。 - John Alexander Betts
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接