Easy Android File Cache

Download code here [download id=”2″]

Licensed under MIT License Copyright (c) 2011 Paul Soucy, (paul+blog@dev-smart.com)

When writing mobile apps, you should constantly be asking yourself: how will my app function when the user goes offline? A well written mobile app should smooth the transition for the user on and offline as much as possible. Usually, this means adopting some agressive caching techniques. I have created an Android cache utility class to help make storing generic data easier. Here is an example of how to use it:

import com.devsmart.android.cache.FileCache; /* * get the stored file's inputstream * @param context * @param uniqueId the unique identifer used when storing the file * */ public InputStream getFile(Context context, String uniqueId){ FileCache cache = FileCache.getFileCache(context); //will return null if uniqueId has not been inserted return cache.get(uniqueId); } /* * * Insert a file into the cache. * @param context * @param uniqueId the unique identifier used to get the file back * sometime in the future. A Url works well. * @param input data to be inserted. The Cache will read the input until * it is empty. */ public void putFile(Context context, String uniqueId, InputStream input { FileCache cache = FileCache.getFileCache(context); cache.put(uniqueId, input); } public void deleteFile(Context context, String uniqueId) { FileCache cache = FileCache.getFileCache(context); cache.delete(uniqueId); }

The FileCache class creates a local sqlite database called filecache.db and a directory called fileCache. When a new file is added, the file’s data is stored in a file under the fileCache directory and an entry is made in the sqlite database.

Paul Soucy

Read more posts by this author.