Ym-Android network framework Volley (practice), androidvolley

Source: Internet
Author: User
Tags http authentication

Ym-Android network framework Volley (practice), androidvolley

I have talked about ym-Android network framework Volley (experience). you should understand the use of volley. Next we will look at how to use volley in practical projects, let's first consider the following questions:

From the previous article, we can see that mQueue only needs one object. The new RequestQueue object is a waste of resources. We should perform unified management on the application and the methods for canceling requests in the 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 */public 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 ApplicationController 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 will be created if it is null */public RequestQueue getRequestQueue() {// lazy initialize the request queue, the queue instance will be// created when it is accessed for the first timeif (mRequestQueue == null) {// 1// 2synchronized (ApplicationController.class) {if (mRequestQueue == null) {mRequestQueue = Volley.newRequestQueue(getApplicationContext());}}}return mRequestQueue;}/** * Adds the specified request to the global queue, if tag is specified then * it is used else Default TAG is used. *  * @param req * @param tag */public <T> void addToRequestQueue(Request<T> req, String tag) {// set the default 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 tag is emptyreq.setTag(TAG);getRequestQueue().add(req);}/** * Cancels all pending requests by the specified TAG, it is 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);}}}
Volley provided many different requests (JsonObjectRequest, JsonArrayRequest, StringRequest, and ImageRequest), but they still could not meet our actual needs, in practice, we often use xml format and Gson parsing.

Next let's take a look at how to customize a 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 ):

public class GsonRequest<T> extends Request<T> {private final Listener<T> mListener;private Gson mGson;private 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 = listener;}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, the last step is to encapsulate the error handling. volley's listening error prompts are all NoConnectionError... Wait, this type of error prompt is obviously not the error prompt we want to present to the user, because even if the user is prompted, it doesn't understand what it means, so we need to encapsulate it, it allows users to better understand these error prompts. Ym -- Volley of the Android network framework (experience) We have discussed that a failed listener must be set for each request:

// 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. We can start from 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. goo Gle. gson. Gson; import com. google. gson. reflect. TypeToken; // As shown in the previous code, you need to add an error listener onErrorResponse when creating a request. If an exception occurs in the request, a VolleyError instance is returned. // The following is a list of Volley exceptions: // AuthFailureError: if an HTTP authentication is performed, this error may occur. // NetworkError: this error occurs when the Socket is disabled, the server goes down, and DNS errors occur. // NoConnectionError: similar to NetworkError, the client has no network connection. // ParseError: when using JsonObjectRequest or JsonArrayRequest, an exception occurs if the received JSON is malformed. // SERVERERROR: The most likely 4xx or 5xx HTTP status code of an error returned by the server. // TimeoutError: the Socket times out. If the server is too busy or the network is delayed, this exception occurs. By default, Volley's timeout is 2.5 seconds. If this error is returned, you can use RetryPolicy. Public class VolleyErrorHelper {/*** Returns appropriate message which is to be displayed to the user against * the specified error object. ** @ param error * @ param context * @ return */public static String getMessage (Object error, Context context) {if (error instanceof TimeoutError) {return context. getResources (). getString (R. string. generic_server_down);} else if (isServerProblem (error) {return h AndleServerError (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 isNetworkProblem (Object error) {return (error instanceof NetworkError) | (error instanceof No ConnectionError);}/*** Determines whether the error is related to server ** @ param error * @ return */private static boolean isServerProblem (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 the server. ** @ param err * @ param context * @ Return */private static String handleServerError (Object err, Context context) {VolleyError error = (VolleyError) err; NetworkResponse response = error. networkResponse; if (response! = Null) {switch (response. statusCode) {case 404: case 422: case 401: try {// server might return error like this {"error ": // "Some error occured"} // Use "Gson" to parse the resultHashMap <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 (); default: return context. getResources (). getString (R. string. generic_server_down) ;}} return context. getResources (). getString (R. string. generic_error );}}

The xml referenced in the above Code is:

<String name = "no_internet"> no network connection ~! </String> <string name = "generic_server_down"> An error occurred while connecting to the server ~! </String> <string name = "generic_error"> network exception. Please try again later ~! </String>
Next, the data request section is finished. Let's talk about it, I personally prefer to use the universal-image-loader instead of the one provided by volley (I think it is more convenient to use the universal-image-loader ). Now we have finished the lecture. You can go to practical development ~! If you do not understand or encounter any problems, you can leave a message for discussion ~!


Can the Volley framework of Android be used for communication with WebService?

No, you also know that velloy uses the http protocol. Webservice uses soap. Two different communication mechanisms

Android development framework

Google's gson package can be used for json parsing.
The Network request and cache mechanism (generally referred to as image cache) can be viewed by volley.
The database is relatively simple. The android app is already encapsulated. But you can check FinalDb in Afinal.
The UI is useless. It is written by yourself. You can master the view and viewgroup. Basically, you can master all the controls.

Related Article

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.