Android about using LRUCache cache data you want to cache

Source: Internet
Author: User

It's been a long time since I wrote a blog.

Today we come to learn about the cache technology, I believe that when you do development is aware of the importance of requesting network data, but there are some only with the request for the outdated information such as some news, if we enter the media every time the new from the internet will inevitably bring bad experience to users, So we need caching technology to help us solve this problem.

1,lrucache Introductionthe Core class is LRUCache (this class is provided in the ANDROID-SUPPORT-V4 package). This class is ideal for caching images, and its main algorithm is to store recently used objects in linkedhashmap with strong references, and to remove the least recently used objects from memory before the cached value reaches a predetermined value. in the past, we often used an implementation of a very popular memory caching technique, either soft or weak (SoftReference or weakreference). However, this is no longer recommended because, starting with Android 2.3 (API Level 9), the garbage collector is more inclined to reclaim objects holding soft or weak references, which makes soft and weak references less reliable. In addition, in Android 3.0 (API level 11), image data is stored in local memory, so it cannot be released in a predictable way, which poses a potential risk of memory overflow and crash of the application. 2,lrucache Usebelow we will write a simple demo to learn LRUCache, the effect is the second time each request is extracted directly from the cache without having to request the network again
/** * Cache JSON data */private Lrucache<integer, string> mjsoncache;/** * Cache picture Information */private Lrucache<integer, Bitmap> ; Mbitmapcache;public Util () {Mjsoncache = new Lrucache<integer, string> (1 * 1024x768 * 1024x768); Mbitmapcache = new lrucache& Lt;integer, bitmap> (2 * 1024 * 1024);} /** * Add into Cache list *  * @param key * @param value */public void Addjsonlrucache (Integer key, String value) {Mjsoncache.put ( Key, value);} public void Addbitmaplrucache (Integer key, Bitmap value) {mbitmapcache.put (key, value);} /** * Take out from the cache list *  * @param key * @return */public String getjsonlrucache (Integer key) {return mjsoncache.get (key);} Public Bitmap Getbitmaplrucache (Integer key) {return mbitmapcache.get (key);}

Can see we are ready to cache bitmap and string, just need to get the information when put into the cache, need to get out, is not very simple, we assigned to our string 1m for our bitmap allocated 2m space, This is just our demo. In order to use this simply, we should consider in more detail how much space should be allocated to the cache.
    Gets the maximum amount of free memory that is used to exceed this value to cause a OutOfMemory exception.     //LRUCache pass through the constructor function to the cache value, in kilobytes.     
In general, the maximum value of about 1/8 is possible.
public class Mainactivity extends Activity implements Onitemclicklistener {private static final String List_data = "http:/ /api.yi18.net/top/list ";p rivate ListView mlistview;private arrayadapter<string> madapter;private ArrayList <Integer> mlistid;private Util util;protected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); util = new Util (); Mlistview = (ListView) Findviewbyid ( r.id.list); Mlistid = new arraylist<integer> (); madapter = new Arrayadapter<string> (this,android. r.layout.simple_list_item_1); Mlistview.setadapter (Madapter); Mlistview.setonitemclicklistener (this); new Downloadjson (). Execute (list_data);}
This section is the normal request data added to the ListView.
private void Getjsondata (String json) {try {jsonobject jsonobject = new Jsonobject (JSON); if (Jsonobject.getboolean (" Success ")) {Jsonarray Jsonarray = Jsonobject.getjsonarray (" yi18 "); for (int i = 0; i < jsonarray.length (); i++) {Jsonobj ECT JsonObject2 = (jsonobject) jsonarray.opt (i); if (I < 5) {Madapter.add (jsonobject2.getstring ("title")); Mlistid.add (Jsonobject2.getint ("id"));}}}} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Class Downloadjson extends Asynctask<string, Void, string> {@Overrideprotected string Doinbackground (String ... params) {return Util.downloadjson (Params[0]);} @Overrideprotected void OnPostExecute (String result) {if (result! = null) {Getjsondata (result);}}}

We simply took the first five data to simulate our news, using the HOT hot word API.


3, Cache

@Overridepublic void Onitemclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {//TODO auto-generated method Stubstring message = Util.getjsonlrucache (Mlistid.get (arg2)); Bitmap Bitmap = Util.getbitmaplrucache (Mlistid.get (arg2)); if (message! = NULL) {Intentnewsinfo (arg2, message, Bitmap);} else {intentnewsinfo (arg2, NULL, NULL);}} public void Intentnewsinfo (int arg2, String message, Bitmap Bitmap) {Intent Intent = new Intent (Mainactivity.this, Newsinf Oactivity.class); Intent.putextra ("message", message), Intent.putextra ("bitmap", bitmap); Intent.putextra ("Index", ARG2); Intent.putextra ("id", Mlistid.get (arg2)); Startactivityforresult (intent, 100);}

you can see that we're here first to find out if there is data in the cache if there is a direct pass to the news details interface, if not then the second interface gets back again.

public class Newsinfoactivity extends Activity {private String news_info = "http://api.yi18.net/top/show?id=";p rivate String imageres[] = {"http://d.hiphotos.baidu.com/image/h%3D360/sign=405b763459afa40f23c6c8db9b65038c/ 562c11dfa9ec8a13508c96e6f403918fa0ecc026.jpg "," http://c.hiphotos.baidu.com/image/h%3D360/sign= 798b4f82caea15ce5eeee60f86013a25/9c16fdfaaf51f3dece3f986397eef01f3a297923.jpg "," http://f.hiphotos.baidu.com/ Image/h%3d360/sign=20a94e03940a304e4d22a6fce1c9a7c3/ac4bd11373f082028719ab3848fbfbedab641b29.jpg ","/HTTP// b.hiphotos.baidu.com/image/h%3d360/sign=3a1af7349145d688bc02b4a294c37dab/ 4b90f603738da977c0f5b82cb351f8198718e3db.jpg "," http://d.hiphotos.baidu.com/image/h%3D360/sign= 75e596560f33874483c5297a610ed937/55e736d12f2eb9381891b2f4d6628535e5dd6f3c.jpg "};p rivate Intent intent;private Util util;private int newId, index;private ImageView imageview;private TextView textview;private Bitmap bitmap;private St Ring message;protected void OnCreate (Bundle savedinstancestate) {Super.onCreate (savedinstancestate); Setcontentview (r.layout.activity_newsinfo); intent = getintent (); util = new Util (); ImageView = (ImageView) Findviewbyid (r.id.image); TextView = (TextView) Findviewbyid (r.id.message); newId = Intent.getextras (). GETINT ("id"), index = Intent.getextras (). GetInt ("index"), if (Intent.getextras (). GetString (" Message ") = NULL) {message = Intent.getextras (). getString (" message "); bitmap = Intent.getparcelableextra (" bitmap "); Textview.settext (html.fromhtml (message)); Imageview.setimagebitmap (bitmap); Toast.maketext (This, "No access to the network Oh,"). Show ();} else {new Downloadjson (). Execute (news_info + newId); new Downloadbitmap (). Execute (Imageres[index]); Toast.maketext (This, "Access network Oh", (). Show ();}} @Overridepublic void onbackpressed () {Intent dataintent = new Intent ();d Ataintent.putextra ("message", message); Dataintent.putextra ("Bitmap", bitmap);d Ataintent.putextra ("NewId", newId); Setresult (dataintent); finish (); Super.onbackpressed ();} private void Getjsondata (String json) {try {Jsonobject Jsonobject = new Jsonobject (JSON), if (Jsonobject.getboolean ("Success")) {Jsonobject jsonObject2 = new Jsonobject ( Jsonobject.getstring ("yi18")); message = jsonobject2.getstring ("message"); Textview.settext (html.fromhtml ( Jsonobject2.getstring ("message")));}} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Class Downloadjson extends Asynctask<string, Void, string> {@Overrideprotected string Doinbackground (String ... params) {return Util.downloadjson (Params[0]);} @Overrideprotected void OnPostExecute (String result) {if (result! = null) {Getjsondata (result);}}} Class Downloadbitmap extends Asynctask<string, Void, bitmap> {@Overrideprotected Bitmap doinbackground (String ... params) {//TODO auto-generated method Stubreturn Util.downloadbitmap (Params[0]);} @Overrideprotected void OnPostExecute (Bitmap result) {if (result! = null) {Bitmap = Result;imageview.setimagebitmap ( result);}}}}

This is more clear, every time we have the information obtained from this interface to LRUCache inside.

@Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {        int newId = Data.getextras () . GetInt ("NewId");        String message = Data.getextras (). getString ("message");        Bitmap Bitmap = Data.getparcelableextra ("Bitmap"); Util.addjsonlrucache (newId, message); Util.addbitmaplrucache ( NewId, bitmap); Super.onactivityresult (Requestcode, ResultCode, data);}

4, Effect



Project Source

Android about using LRUCache cache data you want to cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.