Ym--android Network framework Volley (actual combat article)

Source: Internet
Author: User

Before the Ym--android Network framework Volley (experience), we should understand the use of volley, next we want to see how to use the volley to combat projects inside, we first consider some questions:

From the previous article, Mqueue only needs an object, the new Requestqueue object is a waste of resources, we should be in application, as well as the method of canceling the request can also be unified management in application, see the following code:

Package Com.chronocloud.lib.base;import Android.app.application;import Android.text.textutils;import Com.android.volley.request;import Com.android.volley.requestqueue;import Com.android.volley.volleylog;import Com.android.volley.toolbox.volley;public class Applicationcontroller extends application {/** * Log or request TAG */publ IC static final String TAG = "Volleypatterns";/** * Global request queue for volley */private Requestqueue mrequestqueue;/ * * A Singleton instance of the application class for easy access in other * places */private static Applicationcontrolle R sinstance; @Overridepublic void OnCreate () {super.oncreate ();//Initialize the singletonsinstance = this;} /** * @return Applicationcontroller Singleton instance */public static synchronized Applicationcontroller getinstance () { return sinstance;} /** * @return The volley Request queue, the queue would be created if it is null */public requestqueue getrequestqueue () {/ /lazy Initialize the request queue, the queue instance WIll be//created when it was accessed for the first timeif (mrequestqueue = = null) {//1//2synchronized (Applicationcontro Ller.class) {if (Mrequestqueue = = null) {Mrequestqueue = Volley.newrequestqueue (Getapplicationcontext ());}}} return mrequestqueue;} /** * Adds The specified request to the global queue, if tag is specified then * It's used else Default tag is used. * * @param req * @param tag */public <T> void Addtorequestqueue (request<t> req, String tag) {//Set the DEFAU Lt Tag if tag is Emptyreq.settag (Textutils.isempty (tag)? Tag:tag); VOLLEYLOG.D ("Adding request to queue:%s", Req.geturl ()), Getrequestqueue (). Add (req);} /** * Adds The specified request to the global queue using the Default TAG. * * @param req * @param tag */public <T> void Addtorequestqueue (request<t> req) {//Set the default tag if Ta G is Emptyreq.settag (TAG); Getrequestqueue (). Add (req);} /** * Cancels all pending requests by the specified tag, it's important to * specify a tag so that thE pending/ongoing requests can be cancelled. * * @param tag */public void cancelpendingrequests (Object tag) {if (mrequestqueue! = null) {Mrequestqueue.cancelall (tag); }}}
Nexteven though volley offers us a lot of different request(jsonobjectrequest,jsonarrayrequest,stringrequest,imagerequest , but still can not meet the needs of our actual combat, we often use in real-time development of XML format, Gson parsing.

Now let's look at how to customize the Request

XMLRequest:

public class XMLRequest extends request<xmlpullparser> {private final listener<xmlpullparser> mlistener; Public xmlrequest (int method, String URL, listener<xmlpullparser> listener,errorlistener errorlistener) {super ( method, URL, errorlistener); mlistener = listener;} Public xmlrequest (String URL, listener<xmlpullparser> Listener, Errorlistener errorlistener) {This (Method.get, URL, listener, errorlistener);} @Overrideprotected response<xmlpullparser> parsenetworkresponse (networkresponse Response) {try {String xmlstring = new String (Response.data,httpheaderparser.parsecharset (response.headers)); Xmlpullparserfactory factory = Xmlpullparserfactory.newinstance (); Xmlpullparser Xmlpullparser = Factory.newpullparser (); Xmlpullparser.setinput (new StringReader (xmlString)); return Response.success (Xmlpullparser, Httpheaderparser.parsecacheheaders (Response));} catch (Unsupportedencodingexception e) {return response.error (new ParseError (e))} catch (Xmlpullparserexception e) {return Response.error (new ParseError (e));}} @Overrideprotected void Deliverresponse (Xmlpullparser response) {mlistener.onresponse (response);}}

Gsonrequest (Note that you need to import Gson.jar yourself):

public class Gsonrequest<t> extends request<t> {private final listener<t> mlistener;private Gson Mgson ;p rivate class<t> mclass;public gsonrequest (int method, String URL, class<t> clazz, listener<t> Listener,errorlistener Errorlistener) {Super (method, URL, errorlistener); Mgson = new Gson (); mclass = Clazz;mlistener = Li Stener;} Public gsonrequest (String URL, class<t> clazz, listener<t> listener,errorlistener errorlistener) {This ( Method.get, URL, clazz, Listener, Errorlistener);} @Overrideprotected response<t> parsenetworkresponse (networkresponse Response) {try {String jsonstring = new String (Response.data,httpheaderparser.parsecharset (response.headers)); return Response.success (MGson.fromJson ( Jsonstring, MClass), httpheaderparser.parsecacheheaders (response));} catch (Unsupportedencodingexception e) {return response.error (new ParseError (e));}} @Overrideprotected void Deliverresponse (T response) {mlistener.onresponse (response);}}
next only to the last step is to encapsulate its error handling, the use of volley know that the volley of the monitoring error is noconnectionerror ... And so on, this kind of error hint, obviously this is not we want to give the user to present the error hint, because even if prompt the user also does not understand what meaning, therefore we also need to encapsulate, can let the user see more clearly understand these error hints. Ym--android Network Framework Volley (experience article) we've talked about it. Each request requires a failed listener to be set:

Shared failure callback Private class Strerrlistener implements Errorlistener {@Overridepublic void Onerrorresponse (Volleyerror arg0) { Toast.maketext (Mcontext,volleyerrorhelper.getmessage (arg0, Mcontext), Toast.length_long). Show ();}}
The above code has a Volleyerror object, and we can start with this object:

< Span style= "font-family:arial; Line-height:26px ">

Package Com.example.volley;import Java.util.hashmap;import Java.util.map;import android.content.context;import Com.android.volley.authfailureerror;import Com.android.volley.networkerror;import Com.android.volley.networkresponse;import Com.android.volley.noconnectionerror;import Com.android.volley.servererror;import Com.android.volley.timeouterror;import Com.android.volley.VolleyError; Import Com.google.gson.gson;import com.google.gson.reflect.typetoken;//As seen in the previous code, when you create a request, You need to add an error listener onerrorresponse. If the request has an exception, a Volleyerror instance is returned. The following is a list of exceptions for volley://authfailureerror: This error may occur if you are doing an HTTP authentication. Networkerror:socket shutdown, server down, DNS errors will generate this error. Noconnectionerror: Similar to Networkerror, this is a client with no network connection. ParseError: When using Jsonobjectrequest or jsonarrayrequest, if the JSON received is malformed, an exception is generated. Servererror: An error in the response of the server, most likely the 4xx or 5xx HTTP status code. The Timeouterror:socket times out, the server is too busy, or the network latency causes this exception. By default, the volley time-out is 2.5 seconds. If you get this error, you can use Retrypolicy. public class Volleyerrorhelper {/** * Returns appropriate message which was to being displayed to the user AGAinst * The specified Error object. * * @param error * @param context * @return */public static String getMessage (Object error, Context context) {if (Error I Nstanceof timeouterror) {return context.getresources (). getString (R.string.generic_server_down);} else if ( Isserverproblem (Error)) {return Handleservererror (Error, context),} else if (Isnetworkproblem (Error)) {return Context.getresources (). getString (r.string.no_internet);} Return Context.getresources (). getString (R.string.generic_error);} /** * Determines whether the error is related to network * * @param error * @return */private static Boolean Isnetworkpro Blem (Object error) {return (Error instanceof Networkerror) | | (Error instanceof Noconnectionerror);} /** * Determines whether the error is related to server * * @param error * @return */private static Boolean isserverprobl EM (Object error) {return (Error instanceof Servererror) | | (Error instanceof Authfailureerror);} /** * Handles The server error, tries to determine whether to showA stock * message or to show a message retrieved from the server. * * @param ERR * @param context * @return */private static String handleservererror (Object err, Context context) {Volleye Rror error = (volleyerror) Err; Networkresponse response = error.networkresponse;if (response! = NULL) {switch (response.statuscode) {case 404:case 422:c ASE 401:try {//server might return error like this {' ERROR '://' Some error occured '}//use ' Gson ' to parse the Resultha shmap<string, string> result = new Gson (). Fromjson (New String (Response.data), New typetoken<map<string, String>> () {}.gettype ()), if (result! = null && result.containskey ("error")) {return Result.get ("Error")}} catch (Exception e) {e.printstacktrace ();} Invalid Requestreturn error.getmessage ();d Efault:return context.getresources (). getString (R.string.generic_ Server_down);}} Return Context.getresources (). getString (R.string.generic_error);}}

The XML referenced in the code above is:

<string name= "No_internet" > No Internet connection! </string><string name= "Generic_server_down" > failed to connect server! </string><string name= "Generic_error" > Network anomaly, please try again later! </string>
Next, the data request this piece is already finished, we say this piece, I personally like to useUniversal-image-loader rather than volley himself (the individual thinks it's used.universal-image-loader More Convenient)。 All right, we can go to the actual combat development! Do not understand or encounter problems can leave a message to discuss ~!

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.