Oschina Client Source Learning (2)--The design of the cache

Source: Internet
Author: User

One, the role of caching

When the data is requested, the first judgment is whether the data can be fetched from the cache, and if the condition is met, the data is fetched directly from the cache. Otherwise, the new data is requested. This is more than the case without caching, each time to request data from the server faster, and, without a network, you can also browse the cached data, greatly improving the user experience.

Second, source code analysis

The source used to cache the place is:

1 before requesting data, determine whether it can be fetched from the cache, read directly from the cache if the condition is met, or request new data from the server.

//Get the cached directory PrivateStringGetcachekey() {return NewStringBuilder (Getcachekeyprefix ()). Append ("_"). Append (Mcurrentpage). toString ();}//Request data to determine if data can be fetched from the cache protected void RequestData(BooleanRefresh) {String key = Getcachekey ();if(Isreadcachedata (refresh))        {Readcachedata (key); }Else{//Fetch new dataSendrequestdata (); }    }//Determine if read cache data is required  protected Boolean Isreadcachedata(BooleanRefresh) {String key = Getcachekey ();if(! Tdevice.hasinternet ()) {return true; }//The first page is not active refresh, and the cache exists, taking precedence over the cached        if(Cachemanager.isexistdatacache (Getactivity (), key) &&!refresh && Mcurrentpage = =0) {return true; }//Other pages, cache presence and no expiration, priority cache        if(Cachemanager.isexistdatacache (Getactivity (), key) &&! Cachemanager.iscachedatafailure (Getactivity (), key) && mcurrentpage! =0) {return true; }return false; }

2 Save to cache operation on latest data obtained from server

Private  class savecachetask extends asynctask<void, void , Void> {        Private FinalWeakreference<context> Mcontext;Private FinalSerializable Seri;Private FinalString key;PrivateSavecachetask (context context, Serializable Seri, String key) {Mcontext =NewWeakreference<context> (Context); This. Seri = Seri; This. key = key; }@Override        protectedvoid Doinbackground (void ... params) {Cachemanager.saveobject (Mcontext.get (), Seri, key);return NULL; }    }

Where the Saveobject method is implemented as follows

publicstaticbooleansaveObject(Context context, Serializable ser, String file) {    null;    null;    try {        fos = context.openFileOutput(file, Context.MODE_PRIVATE);        new ObjectOutputStream(fos);        oos.writeObject(ser);        oos.flush();        returntrue;

It's important to note that
(1) Data is an object of the Listentity interface, which inherits the serializable interface, so it is possible to directly pass the parameter.
(2) key is here as a file path (cache directory).

3 Finally, it is worth mentioning (although not much related to the cache), after parsing the returned data, refresh the interface, the processing of the returned data

protected void Executeonloaddatasuccess (List<T>Data){...//compare the data returned by the server with the existing data,//If the same, the sameItemDelete. Last LookDataThe size of the collection//IFDataFinally there are stillItem, the updateListView         for(int I= 0;I<Data.size();I++) {if(CompareTo(Madapter.GetData(),Data.Get(I))) {Data.Remove(I);I--;}} int adapterstate =Listbaseadapter.State_empty_item;if((Madapter.getcount () + data. Size()) = = 0) { adapterstate = listbaseadapter.         State_empty_item; } else if (data.  Size() = = 0|| ( data. Size() < getpagesize() && mcurrentpage = = 0)) { adapterstate = listbaseadapter.             State_no_more; Madapter. notifydatasetchanged        (); } Else { adapterstate = listbaseadapter.         State_load_more; }Madapter.setstate (adapterstate); Madapter.adddata ( data);Judgment equals1is because the last one is the state of the ListView??if(Madapter.getcount () = =1) {if(Needshowemptynodata ()) {Merrorlayout.seterrortype (Emptylayout.NODATA); }Else{Madapter.setstate (Listbaseadapter.State_empty_item);            Madapter.notifydatasetchanged (); }        }    }

Summarize:
More than 1 is the initial source of their own preliminary summary of the understanding and understanding of the cache design, there will certainly be a lot of poor or inaccurate places, hoping to get the general Bo Friends of the guidance. I will try my best to make it perfect.
2 source code in some places, at this stage I do not fully understand, but as long as not affect the general grasp, or can be their understanding and sorting things first to share.

The Xiang
Date: 2015.7.15

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Oschina Client Source Learning (2)--The design of the 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.