How to enable cache - leocadiotine/Dumbledroid GitHub Wiki

Dumbledore can cache your requests automatically and even make you app work offline. This page will show you the instructions to enable it.

##How it works Before every request, Dumbledore will first check if there is a valid cached version. If so, this version will be returned. This approach not only makes the request faster, but also saves data and battery usage.

Every Dumbledroid model has a cache duration. This is what determines if the cached version is valid. In other words, if the cached version is older than its duration, it has expired, and will be discarded.

The cache works in two levels:

  1. Memory: it's faster. Very useful when you make the same requests over and over again;
  2. Disk: slower, but saves data connection and works when your app is offline.

First, Dumbledroid will try to load from memory, because it's faster. If there's no cached version in memory, it will try to load from disk.

Some considerations:

  • The memory cache is not obtrusive, i.e., will not make your app consume a lot of RAM. It's smart, and frees the cache when the garbage collector is needing memory.
  • The disk cache preferably saves the data on the device's SD card. If it's not available, it saves on the internal storage.

##Setup

###Step 1: Add the permission Disk caching requires the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to work. Be sure to add it to your AndroidManifest.xml. If you don't add it, only the memory cache will be used.

###Step 2: Setup the cache duration The duration will vary depending on the model. For example: a blog article is not regularly modified, and can be cached for days. But a Twitter search, in turn, changes its value very quickly and should be cached only for less than a minute.

So the best way to set the cache duration is while calling the super(String url, long cacheDuration) constructor of the AbstractModel. Example (taken from DumbledroidExample):

public class Jedi extends AbstractModel {

	public Jedi() {
		super("YOUR_URL", 15 * 60 * 1000); //15 min cache
	}
}

The cacheDuration parameter is in miliseconds. The default value is 0, which means no cache.

###Step 3: There is no Step 3 You don't need to do anything else :) Caching is already enabled.

##Offline support If you load() a Model while online and try to make the same request again while offline, Dumbledroid will return the last valid cached version for you.