Overriding the create method of LruCache in Android
This is a custom LruCache class extends from LruCache and overrides the create method. The create method is called after a cache miss to compute a value for the corresponding key.
private class DataCache extends LruCache{ public DataCache (int maxSize) { super(maxSize); } @Override protected String create(String key) { // do some important task String s = ""; for (int i=0; i<1000; i++) { s += i + ","; } // take a 3 seconds nap try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } Random r = new Random(); return s.substring(r.nextInt(500), r.nextInt(500) + 400); } }
How to use the above custom LruCache class.
//Initialize the cache to hold a maximum of 10 things. DataCache dataCache = new DataCache(10); //This will get data from the cache if it is available in the cache, else it will go through the create method to create the data and the data will be saved in the cache for future uses. String data = dataCache.get("a_key"); //Remove individual key value dataCache.remove("a_key"); //clear all cache dataCache.evictAll();
Working example of custom LruCache in Android.
MainActivity.java
public class MainActivity extends AppCompatActivity { private static final String KEY = "key"; DataCache dataCache; TextView tvDisplay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvDisplay = (TextView) findViewById(R.id.tv_display); dataCache = new DataCache(10); } public void getData(View v) { long start = System.currentTimeMillis(); String data = dataCache.get(KEY); long end = System.currentTimeMillis(); tvDisplay.setText("time taken: " + (end - start) + "\n" + data); } public void clearCache(View v) { dataCache.remove(KEY); dataCache.evictAll(); } private class DataCache extends LruCache{ public DataCache (int maxSize) { super(maxSize); } @Override protected String create(String key) { // do some nonsenses String s = ""; for (int i=0; i<1000; i++) { s += i + ","; } // take a 3 seconds nap try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } Random r = new Random(); return s.substring(r.nextInt(500), r.nextInt(500) + 400); } } }
activity_main.xml
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts