Caching files using getCacheDir()

Housefly picture Housefly · May 8, 2014 · Viewed 14.3k times · Source

I wanted to download images that are downloaded from Dropbox and cache them for further use:

String cachePath = mContext.getCacheDir().getAbsolutePath() + entry.fileName();
File cacheFile = new File(cachePath);
//cacheFile.exists() returns true after 1st call
if(!cacheFile.exists()){
  //If cache doesn't exist, download the file
  mFos = new FileOutputStream(cachePath);
  mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_320x240,
                              ThumbFormat.JPEG, null);
}
mDrawable = Drawable.createFromPath(cachePath);
mImageView.setImageDrawable(mDrawable);

The mDrawable is null if the code doesn't enter the if block.

If I comment the if condition it works fine. But downloads the images every time.

Edit:

The above code is from how to test for a file in cache

Answer

Biraj Zalavadia picture Biraj Zalavadia · May 8, 2014

Try this hope helps you

String path = context.getFilesDir().getAbsolutePath() + File.separator + entry.fileName();
        File file = new File(path);

        if (file.exists()) {
            // File exists
        } else {
            // File does not exist
        }