Android Batch Image loading classic series--caching with Xutil framework, loading network images asynchronously

Source: Internet
Author: User

First, the problem description

In order to improve the efficiency of picture loading, it is necessary to adopt a cache and asynchronous loading strategy for the image, the coding is relatively complex, there are some excellent frameworks that provide solutions, such as the xutil framework that is more active on git recently.

  The Xutil framework provides four modules:

1, Dbutil module: Using ORM mechanism to simplify sqlite operation, a line of code can perform additions and deletions, support transactions, support delay policy

2, Viewutils module: Can be said to be Android's IOC framework, can be annotated way to bind UI, resources, events

3, Httputils module: Support synchronous, asynchronous request, support large file upload

4, Bitmaputils module: Image of the asynchronous loading, support local and network pictures, image compression processing, image memory cache and local file cache.

This case mainly uses Xutil's Httputils module and Bitmaputils module

Second, Case introduction

To achieve a picture news tour:

Iii. main technology of the case
1. Using Httputils module to realize network communication

(1) Requestparams components set request parameters, upload files and other information

Requestparams params = new Requestparams ("Utf-8"); Default encoding Utf-8params.addquerystringparameter ("CategoryId", "2");//Setting parameters

(2) Httputils component Send request

Httputils http = new Httputils () http.configresponsetextcharset ("Utf-8");//Set the encoding of the returned text, the default encoding utf-8//send the request, set the transfer mode, URL, Pass data, callback component Httputils.send (Httpmethod.post, "Http://192.168.2.178:8080/21-sun/PhotosServlet", params,  new Requestcallback<string> () {                            @Override public                            void OnFailure (HttpException E, String m) {//Execution failed callback method                                     LOG.I ("Jereh", E.getexceptioncode () + "" "+m);                            }                            @Overrid public                            void onsuccess (responseinfo<string> info) {                                     //executes a successful callback method and passes in the data, obtaining the return data through Info.result                            }                          });
2. Asynchronous loading using bitmaputils images

  Use bitmaputils images of asynchronous loading, support local and network pictures, image compression processing.

(1), Bitmapdisplayconfig picture display configuration

   Bitmapdisplayconfig  bigpicdisplayconfig = new Bitmapdisplayconfig ();//Display the original picture, do not compress, try not to use, the picture is too large when easy to oom.   bigpicdisplayconfig.setshoworiginal (true);        Bigpicdisplayconfig.setbitmapconfig (Bitmap.Config.RGB_565);//Set the maximum size of the picture, It is not set when the control property is Adaptive displayconfig.setbitmapmaxsize (Bitmapcommonutils.getscreensize (mactivity));//implements a gradient animation.    alphaanimation animation=new alphaanimation (0.1f,1.0f);    Animation.setduration (+);    Displayconfig.setanimation (animation);

(2) Create Bitmaputils

Structure:

/*** @param Context Context      * @param diskcachepath  Disk cache path      * @param memorycachesize Memory Cache size     * @param Diskcachesize disk cache space Size */bitmaputils (context  context, String  diskcachepath, int  memorycachesize, int  diskcachesize)

Other Forms

Bitmaputils (Context Context) Bitmaputils (context context, String  Diskcachepath) bitmaputils (context  Context,  String diskcachepath, int  memorycachepercent);

Code:

Gets the application maximum available memory        int maxmemory = (int) runtime.getruntime (). MaxMemory ();        int cacheSize = MAXMEMORY/8;        FileUtils fileutils=new FileUtils (mactivity, "Jereh");        Set file cache, memory cache size        bitmaputils  utils=new bitmaputils (Mactivity,fileutils.getcachedir (), cacheSize);

(3) The display () method loads the picture asynchronously and displays it on the view control

Utils.display (T  container, String  uri,   bitmapdisplayconfig   displayconfig);
3, Gson component implementation of JSON data parsing
Gson gson=new Gson ()///Create Gson Component    //JSON data returned by the server, use Gson to parse list<imageinfo> Imageinfo=gson.fromjson (" JSON data ", new Typetoken<arraylist<imageinfo>> () {}.gettype ());
Iv. complete code of the case
1. Photobrowseadapter Adapter Code
public class Photobrowseadapter extends Pageradapter {private Activity mactivity;    Private list<imageinfo> imageList;    Private Layoutinflater inflate;    Private Bitmaputils utils;        Private Bitmapdisplayconfig Displayconfig;        Public Photobrowseadapter (Activity mactivity, list<imageinfo> imageList) {super ();        this.mactivity = mactivity;        This.imagelist = imageList;        Inflate=layoutinflater.from (mactivity);        Gets the application maximum available memory int maxmemory = (int) runtime.getruntime (). MaxMemory ();        int cacheSize = MAXMEMORY/8;        FileUtils fileutils=new FileUtils (mactivity, "Jereh");        Utils=new bitmaputils (Mactivity,fileutils.getcachedir (), cacheSize);        Displayconfig=new Bitmapdisplayconfig (); Displayconfig.setshoworiginal (TRUE);    Display the original picture, do not compress, try not to use, the picture is too large when easy to oom.        Utils.configdefaultbitmapmaxsize (Bitmapcommonutils.getscreensize (mactivity)); Displayconfig.setbitmapmaxsize (Bitmapcommonutils.getscreenSize (mactivity));        Alphaanimation animation=new alphaanimation (0.1f,1.0f);        Animation.setduration (500);    Displayconfig.setanimation (animation);    } @Override public int getcount () {//TODO auto-generated Method stub return Imagelist.size ();        } @Override public boolean isviewfromobject (View arg0, Object arg1) {//TODO auto-generated method stub    return ARG0==ARG1; } @Override Public Object instantiateitem (View container,int position) {Imageinfo Info=imagelist.get (position        );        LinearLayout view= (linearlayout) inflate.inflate (R.layout.phone_item, NULL);        ((TextView) View.findviewbyid (R.id.tvtitle)). SetText (Info.getimgtitle ());        ((TextView) View.findviewbyid (r.id.tvcontent)). SetText (Info.getimgdesc ());        ImageView img= (ImageView) View.findviewbyid (R.id.ivphoto);        Img.settag (Info.getimgurl ());        Utils.display (Img,info.getimgurl (), displayconfig); ((Viewpager) container). AddView (viEW);    return view; } @Override public void Destroyitem (View container,int position,object obj) {((Viewpager) container). Removevi    EW (View) obj; }    }
2. Mainactivity Code
    public class Mainactivity extends Activity {private Viewpager vpimagepager;    Private Photobrowseadapter adapter;    Private list<imageinfo> imageinfolist;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Vpimagepager= (Viewpager) Super.findviewbyid (R.id.vpimgbrowse);        Imageinfolist=new arraylist<imageinfo> ();        Adapter=new Photobrowseadapter (this,imageinfolist);            LoadData ();        } private void LoadData () {requestparams params=new requestparams ();        Params.addquerystringparameter ("CategoryId", "2");//Set Parameters Httputils httputils=new httputils (); Send request to Server Httputils.send (Httpmethod.post, "Http://192.168.2.178:8080/21-sun/PhotosServlet", Params,new requestcal Lback<string> () {@Override public void onfailure (HttpException E, String m) {L OG.I ("Jereh", E.getexceptioncode () + "" +m);                } @Override public void onsuccess (responseinfo<string> info) {///background callback after execution completes and incoming return data  Gson gson=new Gson ()///Create Gson component//JSON data returned by the Info.result server, using Gson parsing list<imageinfo>                Imageinfo=gson.fromjson (Info.result, New typetoken<arraylist<imageinfo>> () {}.getType ());                Imageinfolist.addall (Imageinfo);            Vpimagepager.setadapter (adapter);    }            }); }}
3. Imageinfo entity class and Fileutils tool class
Package picture information public class Imageinfo {    private String imgurl;    Private String Imgtitle;    Private String Imgdesc;    ...//omit}fileutils get File cache directory public class FileUtils {    /** cache file directory */    private file Mcachedir;     Public FileUtils (context context, String Cachedir) {    if (android.os.Environment.getExternalStorageState (). equals (Android.os.Environment.MEDIA_MOUNTED))         Mcachedir = new File (cachedir);      else         Mcachedir = Context.getcachedir ();//How to obtain the system's built-in cache storage path      if (!mcachedir.exists ())            Mcachedir.mkdirs ();    }     Public String Getcachedir () {            return Mcachedir.getabsolutepath ();    }
4. Service-side Photosservlet code
public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexcept    Ion {Response.setcontenttype ("text/json;charset=utf-8");    String categoryid=request.getparameter ("categoryId");//test pass parameter System.out.println (CATEGORYID);    List<imagepart> partlist=new arraylist<imagepart> ();                Imagepart part1=new Imagepart ();    Part1.setimgurl ("http://news.21-sun.com/UserFiles/x_Image/x_20150216131001_0.jpg"); Part1.setimgtitle ("On behalf of China's Dongfeng team, come on!"    ");    Part1.setimgdesc ("...");    Imagepart part2=new Imagepart ();        Part2.setimgurl ("http://news.21-sun.com/UserFiles/x_Image/x_20150216131432_0.jpg");        Part2.setimgtitle ("Sanya Regatta Experience Tour");        Part2.setimgdesc ("...");        Imagepart part3=new Imagepart ();        Part3.setimgurl ("http://news.21-sun.com/UserFiles/x_Image/x_20150216131157_0.jpg");        Part3.setimgtitle ("Volvo Group president and CEO Orov Payson and Volvo");        Part3.setimgdesc ("..."); Partlist.add (part1);p artlist.adD (part2);p artlist.add (PART3);        Jsonarray Jsonarray=jsonarray.fromobject (partlist,config);    Response.getwriter (). println (Jsonarray.tostring ()); }

To learn more about the small partners, you can click to view the source code , run the test yourself.

Inquiries or technical exchanges, please join the official QQ Group: (452379712)

Jerry Education
Source:http://blog.csdn.net/jerehedu/
This article is the copyright of Yantai Jerry Education Technology Co., Ltd. and CSDN Common, welcome reprint, but without the author's consent must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Android Batch Image loading classic series--caching with Xutil framework, loading network images asynchronously

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.