Android: about using LruCache to cache the data you want to cache, androidlrucache

Source: Internet
Author: User

Android: about using LruCache to cache the data you want to cache, androidlrucache

I haven't written a blog for a long time ..

Today, let's take a look at the cache technology. I believe everyone knows the importance of requesting network data during development. However, there are some outdated messages that only use one request, such as some news information, every time we enter the news interface, getting a new one from the Internet will inevitably bring a poor user experience, so we need the cache technology to help us solve this problem.

1. LruCache introduces the core class LruCache (this class is provided in the android-support-v4 package ). This class is very suitable for caching images. Its main algorithm principle is to store recently used objects with strong references in javashashmap, in addition, the minimum recently used objects are removed from the memory before the cache value reaches the preset value. In the past, we often used the implementation of a very popular memory cache technology, namely, SoftReference or WeakReference ). However, this method is no longer recommended, because since Android 2.3 (API Level 9), the garbage collector prefers to recycle objects that hold soft or weak references, this makes soft references and weak references no longer reliable. In addition, in Android 3.0 (API Level 11), image data is stored in the local memory, so it cannot be released in a foreseeable way, this poses a potential risk of application memory overflow and crash. 2. LruCache uses the following code to write a simple demo to learn LruCache. The result is that each request is extracted from the cache for the second time without requesting the network again.
/*** Cache json data */private LruCache <Integer, String> mJsonCache;/***** cache image information */private LruCache <Integer, Bitmap> mBitmapCache; public Util () {mJsonCache = new LruCache <Integer, String> (1*1024*1024); mBitmapCache = new LruCache <Integer, Bitmap> (2*1024*1024 );} /*** add to the 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);}/*** get it 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 );}

We can see that we are preparing to cache Bitmap and String. We only need to put the information into the cache when we get it, and get it when we need it, isn't it very simple, we allocated 1 MB for our String to allocate 2 MB space for our Bitmap. This is just the purpose of our demo, in fact, we should consider in detail how much space should be allocated to the cache.
// Obtain the maximum available memory. exceeding this value will cause an OutOfMemory exception. // LruCache transmits the cache value through the constructor, in KB. Int maxMemory = (int) (fig. getRuntime (). maxMemory ()/1024 );
Generally, the maximum value is about 1/8.
public class MainActivity extends Activity implements OnItemClickListener {private static final String LIST_DATA = "http://api.yi18.net/top/list";private 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 adds common request data to 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++) {JSONObject 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 pieces of data to simulate our news, using the popular buzzword 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, NewsinfoActivity.class);intent.putExtra("message", message);intent.putExtra("bitmap", bitmap);intent.putExtra("index", arg2);intent.putExtra("id", mListId.get(arg2));startActivityForResult(intent, 100);}

We can see that here we first look for the existence of data in the cache, if there is direct to the news details interface, if not, then get it on the second interface and then pass it back.

Public class NewsinfoActivity extends Activity {private String NEWS_INFO = "http://api.yi18.net/top/show? Id = "; private 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/ac4bd11373f082028719ab3848fbfbed Ab641b29.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 "}; private Intent intent; private Util util; private int newId, index; private ImageView imageView; private TextView textView; private Bit Map bitmap; private String 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. getEx Tras (). getString ("message ")! = Null) {message = intent. getExtras (). getString ("message"); bitmap = intent. getParcelableExtra ("bitmap"); textView. setText (Html. fromHtml (message); imageView. setImageBitmap (bitmap); Toast. makeText (this, "No network access", 2000 ). show ();} else {new downloadjson(cmd.exe cute (NEWS_INFO + newId); new downloadbitmap(cmd.exe cute (imageRes [index]); Toast. makeText (this, "network access", 2000 ). show () ;}@ Overridepublic void onBackPresse D () {Intent dataIntent = new Intent (); dataIntent. putExtra ("message", message); dataIntent. putExtra ("bitmap", bitmap); dataIntent. putExtra ("newId", newId); setResult (20, 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 (Stri Ng 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 quite clear. Every time we store the information we get from this interface in LruCache.

@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 code

Related Article

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.