Reprint Please indicate this article from CYM's blog (http://blog.csdn.net/cym492224103 ). Thank you for your support.
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 need an object to be able, new Requestqueue object to resources a waste, we should in application. and the ability to put the cancellation request method also in application for unified management, 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); }}}
Nextis volley despite the very many different request(jsonobjectrequest,jsonarrayrequest,stringrequest,imagerequest ). But still can not meet the needs of our actual combat, our actual combat development is often used in the XML format, Gson parsing.
And then we'll see how to define 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 the 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. Volley's listening error hints areNoconnectionerror.
。
Wait, this kind of error hint, obviously this is not we want to give the user to present the error hint, because even prompt the user also not clear what meaning. So we're going to wrap it up. Allows the user to see more clearly 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:
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 creating a request, you need to add an error listener onerrorresponse. Assuming that the request has an exception, a Volleyerror instance is returned. The following is an exception list 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 Internet connection. ParseError: When using Jsonobjectrequest or jsonarrayrequest, it is assumed that the JSON received is malformed and produces an exception. 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.
Assume that you can use Retrypolicy to get this error. public class Volleyerrorhelper {/** * Returns appropriate message which was to being displayed to the user against * the Speci Fied 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 show a stock * message or to show a message retrieved from T He 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);}} ReturnContext.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 finished, let's say this piece. I personally like to useUniversal-image-loader rather than volley own (personally feel used upuniversal-image-loader More Convenient)。
All right, we're done. We can go to the actual combat development ~!
Do not understand or encounter problems can message discussion ~!
Ym--android Network framework Volley (actual combat article)