Android Batch Image loading classic series--volley framework for a multi-layout news list

Source: Internet
Author: User

First, the problem description

Volley is a Google 2013 release of the implementation of the Android Platform network Communication library, mainly provide network communications and image download solutions, such as the previous steps to download pictures from the Internet may be such a process:

Start reading the image in ListAdapter's GetView ().

using HttpURLConnection to go from the server through Asynctask and other mechanisms, set the properties of the corresponding ImageView in the Asynctask OnPostExecute (). and in volley, only need imageloader can be realized.

Case Introduction--   now Picture news view:

Ii. main components of the case

1, the Requestqueue request queue will stringrequest the request into the queue, and asynchronous processing, the main code:

Create Requestqueue to send asynchronous request Requestqueue  Mrequestqueue=volley.newrequestqueue (this);//stringrequest request=new Stringrequest (...); /Create a client request Mrequestqueue.add (request);//Add requests to the queue and execute the request asynchronously

2. Imageloader cache and load network images asynchronously

Create a Imageloader to cache and take pictures from the cache//The first parameter is the Requestqueue object created earlier//The second parameter is the picture cache setting, see Bitmapcache code Imageloader Mimageloader=new Imageloader (mrequestqueue,new bitmapcache ());//Load picture, first load from memory, memory no longer load from network//url: Picture network path  //view Display picture of the ImageView control, R.drawable.default does not load the finished display of the default picture, R.drawable.error load failed to display the picture        mimageloader.get (URL, Imageloader.getimagelistener (view,                R.drawable.default, R.drawable.error));    
Three, the case complete code

Note: Service-side environments need to be built on their own

1, Bitmapcache and sunnewsapplication components:

  (1) Bitmapcache:

public class Bitmapcache implements imagecache{    private lrucache<string, bitmap> Mcache;    Public Bitmapcache () {    ///Gets the maximum available memory, using memory exceeding this value causes the OutOfMemory exception    //uses 1/8 of the maximum available memory value as the size of the cache.    int maxsize= (int) (Runtime.getruntime (). MaxMemory ()/1024)/8;    Mcache=new lrucache<string, bitmap> (maxsize) {    //override this method to measure the size of each picture, returning the number of pictures by default            @Override            protected int sizeOf (String key, Bitmap value) {                return super.sizeof (key, value);            }        };    }    /**     * Get cached Picture *    /@Override public    Bitmap getbitmap (String key) {        return mcache.get (key);    }    /**     * Cache *     /    @Override public    void Putbitmap (String key, Bitmap Bitmap) {        if (bitmap!= NULL) Mcache.put (key, bitmap);}    }

(2) Sunnewsapplication:

public class Sunnewsapplication extends application {private Imageloader mimageloader;       Private Requestqueue mrequestqueue;public void OnCreate () {//create Requestqueue, can send asynchronous request mrequestqueue= Volley.newrequestqueue (this);//create Imageloader to cache and remove pictures from the cache mimageloader=new Imageloader (mrequestqueue,new Bitmapcache ());        }    Public Imageloader Getmimageloader () {        return mimageloader;    }    Public Requestqueue Getmrequestqueue () {        return mrequestqueue;    }}

2, Morestylenewslistviewadapter code:

public class Morestylenewslistviewadapter extends Baseadapter {private Activity mactivity;    Private list<newsitem> newslist;    Private Imageloader Imageloader;        Public Morestylenewslistviewadapter (Activity mactivity,list<newsitem> newslist) {this.mactivity=mactivity;        This.newslist=newslist;    Imageloader= ((sunnewsapplication) mactivity.getapplication ()). Getmimageloader ();    } private final int type_count=2; /** * Returns data item display type Data */@Override public int getitemviewtype (int position) {return newslist!=null?news    List.get (position). GetStyle ():-1;    }/** * Returns the number of types */@Override public int getviewtypecount () {return type_count;    } @Override public int getcount () {return newslist.size ();    } @Override public Object getItem (int position) {return newslist.get (position);    } @Override public long getitemid (int position) {return position; } @Override PublIC view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder=null;        NewsItem Item=newslist.get (position);        if (convertview==null) {holder=new viewholder (); Convert Layout.xml to view switch (Item.getstyle ()) {Case 0:convertview=layoutinflater.from (mactivi                ty). Inflate (r.layout.news_item1, NULL);                holder.ivimg1= (ImageView) Convertview.findviewbyid (r.id.ivnewsimg);            Break                Case 1:convertview=layoutinflater.from (mactivity). Inflate (r.layout.news_item2, NULL);                holder.ivimg1= (ImageView) Convertview.findviewbyid (R.ID.IVIMG1);                Holder.ivimg2= (ImageView) Convertview.findviewbyid (R.ID.IVIMG2);                holder.ivimg3= (ImageView) Convertview.findviewbyid (R.ID.IVIMG3);            Break            } holder.tvtilte= (TextView) Convertview.findviewbyid (r.id.tvtitle);         Convertview.settag (holder);//Record an identity}else{   Holder= (Viewholder) Convertview.gettag (); }//Bind data to UI element Holder.tvTilte.setText (Item.gettitle ());//load picture, load from memory first, memory no longer load from network Imageloader.get (item. Getimgurl () [0], Imageloader.getimagelistener (HOLDER.IVIMG1, R.drawable.default_big, R.drawable.default_big)                );                        Switch (Item.getstyle ()) {Case 1:imageloader.get (Item.getimgurl () [1], Imageloader.getimagelistener (HOLDER.IVIMG2,                    R.drawable.default_big, R.drawable.default_big)); Imageloader.get (Item.getimgurl () [2], Imageloader.getimagelistener (HOLDER.IVIMG3, R.drawable.default                    _big, R.drawable.default_big));        Break        } log.d ("Jereh", "GetView ()");    return convertview;        } private class viewholder{private TextView tvtilte;        Private ImageView IVIMG1;        Private ImageView IvImg2;        Private ImageView IVIMG3; }}

3, mainactivity code

public class Mainactivity extends Activity {private Radiogroup rgchannel;    Private list<newsitem> newslist=new arraylist<newsitem> ();    Private Morestylenewslistviewadapter adapter;    Private ListView Newslistview;    Private Requestqueue queue;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_home);        Queue= ((sunnewsapplication) super.getapplication ()). Getmrequestqueue ();        Initview ();        RequestData ();        } private void Initview () {rgchannel= (Radiogroup) Super.findviewbyid (R.id.rgchannel);        Rgchannel.check (R.id.rbtoday);        newslistview= (ListView) Super.findviewbyid (r.id.lvnews);        Adapter=new Morestylenewslistviewadapter (this,newslist);    Newslistview.setadapter (adapter); /** * Asynchronous request for network data */private void RequestData () {String url= "http://192.168.0.107:8080/21-sun/Ne        Wslistservlet ";Stringrequest request=new stringrequest (Method.get,url, New response.listener<string> () {@Overri                De public void Onresponse (String ret) {//requests a successful call and returns the result Gson gson=new Gson ();                List List=gson.fromjson (ret, new typetoken<arraylist<newsitem>> () {}.gettype ());                Newslist.addall (list);            Adapter.notifydatasetchanged (); }}, new Response.errorlistener () {@Override public void Onerrorresponse (volleyerror error) {//Request failed to call LOG.D ("Jereh", "Network Load failed!            ");        }        }); Queue.add (request);//Add requests to queue, execute requests asynchronously}}

4. NewsItem entity class

public class NewsItem {private String title;//news title    private int style;//0: Normal 1: Multi Figure 2:        private string[] imgurl;//news Map Slice        ...//Omit Setter/getter}

5. Service-Side Newslistservlet code

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexceptio    n {response.setcontenttype ("text/json;charset=utf-8");    List<newsitem> newslist=new arraylist<newsitem> ();    NewsItem item1=new NewsItem ();    Item1.settitle ("The British reached the only Xinjiang's highest credit rating of the maintenance of construction enterprises");    Item1.setstyle (0);    Item1.setimgurl (New string[]{"Http://news.21-sun.com/UserFiles/x_Image/x_20150624164627_0.jpg"});    Newslist.add (ITEM1);    NewsItem item4=new NewsItem ();    Item4.settitle ("German Workers 2015 road machinery quality in the thousands of activities into Henan"); Item4.setstyle (1); Item4.setimgurl (newstring[]{"http://news.21-sun.com/UserFiles/x_Image/x_20150624101251_0.jpg "," Http://news.21-sun.com/UserFiles/x_Image/x_20150624080852_0.jpg "," http://news.21-sun.com/UserFiles/x_Im    Age/x_20150623141354_0.jpg "});            Newslist.add (ITEM4);    NewsItem item5=new NewsItem ();    Item5.settitle ("Texas Bao Ding General manager Wang Guiqing: Really women love learning");    Item5.setstyle (0); Item5.setimgurl (New string[]{"Http://news.21-sUn.com/userfiles/x_image/x_20150624123300_0.jpg "});    Newslist.add (ITEM5);    Jsonarray Jsonarr=jsonarray.fromobject (newslist);    System.out.println (Jsonarr); Response.getwriter (). Print (jsonarr.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--volley framework for a multi-layout news list

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.