Related articles
Android Network Programming (i) HTTP protocol principle
Android Network Programming (ii) HttpClient and HttpURLConnection
Preface
Volley presumably a lot of people have used, in order to set up a knowledge system of network programming, volley is a must speak of knowledge points, so I need to introduce once again the use of volley.
1.Volley Introduction
A new network communication framework, volley, was launched in 2013 at the Google I/O conference. Volley can not only access the network to obtain data, but also can load pictures, and in performance has also made a large adjustment, its design goal is very suitable for the data volume is not small, but the traffic is frequent network operation, and for large data volume of network operations, such as downloading files, etc. Volley's performance will be very bad. Before using volley, download the volley library and place it in the Libs directory and add it to the project. Download Volley please click here
2.Volley Network request queue
Volley request the network is based on the request queue, developers just put the request in the request queue, the request queue will be requested in turn, in general, an application if the network request is not particularly frequent, there can be only one request queue (corresponding to application), If there is a lot or other situation, then it can be an activity corresponding to a network request queue, which depends on the situation, first create the queue:
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
usage of 3.StringRequest
The data returned by Stringrequest is of type string and we look at the source code for the next stringrequest:
Public class stringrequest extends Request<String> { Private FinalListener<string> Mlistener; PublicStringrequest (intmethod, String URL, listener<string> Listener, Errorlistener errorlistener) {Super(method, URL, errorlistener); This. Mlistener = Listener; } PublicStringrequest (String URL, listener<string> Listener, Errorlistener errorlistener) { This(0, URL, Listener, errorlistener); }... Omitted
There are two constructors, the first of which is one more request than the second, and if the second one is a GET request by default. OK, let's try to ask Baidu with a Get method:
//Create request queueRequestqueue mqueue = Volley.newrequestqueue (Getapplicationcontext ()); Stringrequest mstringrequest =NewStringrequest (Request.Method.GET,"Http://www.baidu.com",NewResponse.listener<string> () {@Override Public void Onresponse(String response) {LOG.I ("Wangshu", response); } },NewResponse.errorlistener () {@Override Public void Onerrorresponse(Volleyerror error) {LOG.E ("Wangshu", Error.getmessage (), error); } });//Add the request to the request queueMqueue.add (mstringrequest);
Of course, don't forget to add Network access:
<uses-permission android:name="android.permission.INTERNET"/>
The request result Needless to say is the Baidu interface HTML file:
usage of 4.JsonRequest
Similar to Stringrequest, we are directly on the code:
Requestqueue mqueue = Volley.newrequestqueue (Getapplicationcontext ()); Jsonobjectrequest mjsonobjectrequest =NewJsonobjectrequest (Request. Method.post,"Http://api.1-blog.com/biz/bizserver/article/list.do",New Response. Listener<jsonobject> () {@Override Publicvoid Onresponse (JsonobjectResponse) {Log. D ("Wangshu",Response. toString ()); } },New Response. Errorlistener () {@Override Publicvoid Onerrorresponse (VolleyerrorError) {Log. E ("Wangshu",Error. GetMessage (),Error); } } ); Mqueue.add (mjsonobjectrequest);
The running program returns a bunch of news JSON data:
To parse the JSON data, we use Gson to parse the JSON data. Click here to download Gson to place the jar package in the Libs directory and add it into the project. We started writing the article Class for storing data:
Public classArticle {PrivateString desc;PrivateString status;Privatelist<detail> detail =NewArraylist<detail> (); PublicList<article.detail>Getdetail() {returnDetail } Public void Setdetail(list<article.detail> detail) { This. detail = detail; } PublicStringGetDesc() {returnDesc } Public void Setdesc(String desc) { This. desc = desc; } PublicStringGetStatus() {returnStatus } Public void SetStatus(String status) { This. Status = Status; } Public classDetail {PrivateString title;PrivateString Article_url;PrivateString my_abstract;PrivateString Article_type; PublicStringGetTitle() {returnTitle } Public void Settitle(String title) { This. title = title; } PublicStringGetarticle_url() {returnArticle_url; } Public void Setarticle_url(String Article_url) { This. Article_url = Article_url; } PublicStringgetmy_abstract() {returnMy_abstract; } Public void setmy_abstract(String my_abstract) { This. my_abstract = My_abstract; } PublicStringGetarticle_type() {returnArticle_type; } Public void Setarticle_type(String Article_type) { This. Article_type = Article_type; } }}
Finally we rewrite the jsonrequest request callback:
Requestqueue mqueue = Volley.newrequestqueue (Getapplicationcontext ()); Jsonobjectrequest mjsonobjectrequest =NewJsonobjectrequest (Request. Method.post,"Http://api.1-blog.com/biz/bizserver/article/list.do",New Response. Listener<jsonobject> () {@Override Publicvoid Onresponse (JsonobjectResponse) {article marticle=NewGson (). Fromjson (Response. toString (), article.class); List<article.detail>mlist=marticle.getdetail ();StringTitle=mlist.Get(0). GetTitle ();Log. D ("Wangshu", title); } },New Response. Errorlistener () {@Override Publicvoid Onerrorresponse (VolleyerrorError) {Log. E ("Wangshu",Error. GetMessage (),Error); } } ); Mqueue.add (mjsonobjectrequest);
To see the print results:
5. Loading pictures with imagerequest
Imagerequest is a deprecated method, similar to the previous two usages:
Requestqueue mqueue = Volley.newrequestqueue (Getapplicationcontext ()); Imagerequest imagerequest =NewImagerequest ("Http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg",NewResponse.listener<bitmap> () {@Override Public void Onresponse(Bitmap response) {Iv_image.setimagebitmap (response); } },0,0, Bitmap.Config.RGB_565,NewResponse.errorlistener () {@Override Public void Onerrorresponse(Volleyerror error) {Iv_image.setimageresource (R.drawable.ico_default); } }); Mqueue.add (imagerequest);
View Imagerequest source Discovery It can set the maximum width and height of the picture you want, and if the picture exceeds the desired maximum width and height when loading the picture, it will compress:
Public imagerequest(String URL, listener<bitmap> Listener,intMaxWidth,intMaxHeight, ScaleType ScaleType, Config decodeconfig, Errorlistener errorlistener) {Super(0, URL, errorlistener); This. Setretrypolicy (NewDefaultretrypolicy ( +,2,2.0F)); This. Mlistener = Listener; This. mdecodeconfig = Decodeconfig; This. mmaxwidth = MaxWidth; This. mmaxheight = MaxHeight; This. Mscaletype = ScaleType; }
6. Loading pictures with Imageloader
Imageloader's internal use of the imagerequest to implement, its constructor can pass in a imagecache cache parameters, the implementation of the image cache function, but also can filter the duplicate links, to avoid repeated sending requests.
Requestqueue Mqueue = Volley (Getapplicationcontext ()) Imageloader Imageloader = new Imageloader (Mqueue, New Bitmapcache ()) Imageloader listener = Imageloader.getimagelistener (iv_image,r< Span class= "Hljs-preprocessor" >.drawable .ico _default, R.drawable .ico _default) Imageloader.get ( "http://img.my.csdn.net/ Uploads/201603/26/1458988468_5804.jpg ", listener)
Unlike the imagerequest implementation effect, the Imageloader load picture will display the default picture first, waiting for the picture to be loaded before it appears on the ImageView.
Of course Imageloader also provides a way to set the maximum width and height:
publicgetintint maxHeight) { returnthis.get(requestUrl, imageListener, maxWidth, maxHeight, ScaleType.CENTER_INSIDE); }
7. Loading pictures with Networkimageview
Networkimageview is a custom control that inherits from ImageView and encapsulates the ability to request a network load picture.
Refer to the layout first:
<com .android .volley .toolbox android:id= "@+id/nv_image" android:layout_width=
"200DP"
android:layout_height= "200DP" Android : Layout_centerhorizontal= android:layout_below= "@id/iv_image" android:layout_margintop= "20DP" ></com .android .volley .toolbox ;
Called in code, similar to the Imageloader usage:
Iv_image = (ImageView) This. Findviewbyid(R. ID. IV_image);Requestqueue Mqueue = Volley. Newrequestqueue(Getapplicationcontext ());Imageloader Imageloader = new Imageloader (Mqueue, New Bitmapcache ());Nv_image. Setdefaultimageresid(R. drawable. ico_default);Nv_image. Seterrorimageresid(R. drawable. ico_default);Nv_image. Setimageurl("Http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg", Imageloader);
Networkimageview does not provide a way to set the maximum width and height, according to our settings control the width and height of the network picture of the width and height of the interior will automatically go to implement compression, if we do not want to compress can be set Networkimageview control width and height are wrap_ Content
GitHub Source Download
Android Network Programming (iii) Volley usage full analysis