<span id="Label3"></p><p><p>Most of the Android application development involves network operation, and in the network operation is mostly HTTP operation, you may choose Java httpurlconnection, may also be Apache httpclient, For a high-level package, Google's Pro-son volley, as well as many third-party frameworks such as Okhttp,xutils.</p></p><p><p>And I am more inclined to use Google's volley in development, after all, pro-son, although it is more complicated than some three-way, but we can completely encapsulate it ourselves, this blog, we go to the height of packaging volley, let volley look better.</p></p><p><p>What is your ideal package?<br></p></p><pre class="brush:java;toolbar:false;"><pre class="brush:java;toolbar:false;">Net.url (). params (). parser (). get ();</pre></pre><p><p>Let's see if this package is right for your appetite, or we'll simplify it a little bit, like this:<br></p></p><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">Net.get (url, params, parser, Callback)</pre></pre><p><p>Today we will implement the second mode of operation of the package!</p></p><p><p>Analyze the parameters, URL Needless to say, params we directly use map? no, It's definitely a simple package for the map, why encapsulate it? Volley need is the map format parameters ah? We still need a shape like:</p></p><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">New Requestparams (). put (). put ().</pre></pre><p><p>Such cascading operations, the encapsulation is very simple, see the code:</p></p><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">/** * Send Network Request * The Parameter object of the POST method * @author Loader * */public class Requestparams {private linkedhashmap<string, string> m Params;public requestparams () {mparams = new linkedhashmap<string, string> ();} /** * Add parameter * @param key * @param value * @return */public requestparams add (String key, Object value) {mparams.put (key , value.tostring ()); return this;} Public linkedhashmap<string, string> get () {return mparams;}}</pre></pre><p><p>Not much to say, go on to the next parameter what's parser,parser? Of course is used to parse the return value of the network request, Most of the case is to return json, of course, it may be xml, then why not in the callback to parse it? This is mainly for the understanding of Decoupling. That is, the parsing part of the code does not affect callback, the second advantage is that parser and callback can be developed in parallel, write callback coder can and write parser parallel development, even before Coder. Having said so many parser benefits, let's take a quick look at what parser is.<br></p></p><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">/** * Parse Data * @author loader * @param <T> */public interface parser<t> {public result<t> parse (String Res ponse);}</pre></pre><p><p>is simply an interface, and the return value is a generic of result, look at result:</p></p><pre class="brush:java;toolbar:false">/** * * @author loader * * @param <T> */public class result<t> {public static final int err = 0; // Errorpublic static final int ok = 1; // okprivate int status ; // Status ERR OKprivate String msg; // error information private t result; // Results private object obj; // additional public int getstatus () { return status;} Public void setstatus (int status) {this.status = status;} Public string getmsg () {return msg;} Public void setmsg (string msg) {this.msg = msg;} Public t getresult () {return result;} Public void setresult (t result) {this.result = result;} Public object getobj () {return obj;} Public void&nbSp;setobj (object obj) {this.obj = obj;} Public boolean isok () {return status == ok;}}</pre><p><p>Two constants, which represent success and failure, the value of status is selected in Err and ok, msg is the reason for failure, it is possible to succeed without it, result is our result, and an obj is a value added, sometimes we may want to return more than one of the values (refer to the message).</p></p><p><p>The most important thing here is that t-result, this t is what we specify when we write Parser. That is what kind of parser we want to return, and what kind of results we have.</p></p><p><p>Go back to parser and say that he is an interface, that for my project, I also provide an abstract base class to See:</p></p><pre class="brush:java;toolbar:false">Base classes for/** * parsers * @author loader * * @param <t> */public abstract class absparser<t> implements parser<t> {@Overridepublic result<t> parse (string response) {Result<T> result = new result<t> (); Try {jsonobject baseobject = new jsonobject (response); Baseobject.optboolean ("success")) throw new exception (baseobject.optstring ("message")); Result.setstatus (result.ok);p Arseresponse (baseobject, result);} catch (exception e) {result.setstatus (result.err); result.setmsg (e.getmessage ()); E.printstacktrace ();} return result;} /** * parsing JSON content * @param baseObject * @return */public abstract void parseresponse (jsonobject baseobject, result<t> result) throws Exception;}</pre><p><p>here, we implement the parse method, parsing the common part in the parse method, and providing an abstract Parseresponse method for the user to extend the Parsing.</p></p><p><p>There is also a callback, also an interface, we need to implement Ourselves:</p></p><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">/** * Callback Data * @author Loader * @param <T> */public interface callback<t> {public void onsuccess (result<t> Result);p ublic void onfailed (String msg);</pre></pre><p><p>When success returns to result, failure is a message.</p></p><p><p>oh, yes, What about the volley package? The attentive friend may have found a volleymanager, to look at:</p></p><pre class="brush:java;toolbar:false">/** * Package volley * @author loader * */public class volleymanager {private RequestQueue mRequestQueue;private static VolleyManager sInstance; Public synchronized static volleymanager getinstance () {if (sInstance == Null) sinstance = new volleymanager (); return sinstance;} Private volleymanager () {mrequestqueue = volley.newrequestqueue (App.getInstance ());} /** * Add a request * @param request */public <t> void add <t> request) {mrequestqueue.add (request);} /** * add a request and set tag * @param request * @param tag */public <t> void add (request<t> request, object tag) {request.setTag (tag); Add (request);} /** * Cancel all requests */public void cancelall () {mrequestqueue.cancelall (neW requestqueue.requestfilter () {@Overridepublic boolean apply (request<?> Request) {return true;});} /** * cancellation of the specified tag request * @param tag */public void cancel (object tag) {mrequestqueue.cancelall (tag);}}</pre><p><p>Provides a single example to add a Request.</p></p><p><p>well, The encapsulation code is all that, let's take a look at using it.</p></p><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">/** * * @author loader * */public class userbiz {/** * User Login * @param phonenumber * @param pwd * @param li */public void l Ogin (final string phonenumber, final string pwd,final callback<boolean> Callback) {String url = constants.login_url + "? mobile=" + phonenumber + "&password=" + pwd + "&apptype=2&type=2"; Net.get (url, new Loginparser (), callback);}}</pre></pre><p><p>Keep Looking at loginparser:</p></p><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">Class Loginparser extends absparser<boolean> {@Overridepublic void Parseresponse (jsonobject baseobject, Result <Boolean> Result) throws Exception {if (baseobject.optboolean ("success")) {jsonobject dataObject = null;if ( Baseobject.has ("userinfo")) {dataObject = Baseobject.optjsonobject ("userinfo");} else if (baseobject.has ("barberinfo")) {dataObject =baseobject.optjsonobject ("barberinfo");} if (dataObject = = Null) {result.setstatus (result.err); return;} User user = new user (); onuserinfo (dataObject, user); result.setstatus (result.ok); Result.setresult ( Baseobject.optboolean ("success"));} else {result.setstatus (result.err), result.setmsg (baseobject.optstring ("message"));}}}</pre></pre><p><p>According to your own parsing results to assign value, until now the result has come out, then need to callback callback to the Ui:</p></p><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">Muserbiz.login (mphonenumber, mpassword, mloginlistener);</pre></pre><pre class="brush:java;toolbar:false"><pre class="brush:java;toolbar:false">Private callback<boolean> Mloginlistener = new callback<boolean> () {@Overridepublic void onfailed (String Msg) {log.debug ("failed:" + msg);} @Overridepublic void onsuccess (result<boolean> Result) {Boolean success = Result.getresult (); if (!success) { Log.debug ("login failed"); return;} TODO: success after your logic}};</pre></pre><p><p>In mloginlistener, different logic is made according to the results of Result.</p></p><p><p>ok, this time a simple volley package is complete, and realize the separation of parser and callback, is not very cool? Of course you may also put the parser part in the callback, nothing is not possible, depending on your project.</p></p><p><p>This article is from the "loader" blog, make sure to keep this source http://loader.blog.51cto.com/4845568/1678301</p></p><p><p>Android development for the volley package</p></p></span>
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