Android-volley Network communication Framework (Stringrequest & Jsonobjectrequest)

Source: Internet
Author: User

1. Recall

In the last chapter, the volley is introduced and the purpose and goal of learning it, and finally, some preparation for learning volley


2. Focus

Establishment of 2.1 Requestqueue request queue

2.2 Learn stringrequest and jsonobjectrequest.


establishment of 3.RequestQueue request queue

The new class Volleyapplication inherits from application and uses singleton mode to create the request processing queue, for example:


Package Com.example.volleyhttp;import Com.android.volley.requestqueue;import Com.android.volley.toolbox.Volley; Import Android.app.application;public class Volleyapplication extends application {/** * 01. Create  Request queue * 02. Increase the request queue to Androidmain.xml in *.  */private static requestqueue queue, @Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); Queue=volley.newrequestqueue (Getapplicationcontext ());} Ingress public static Requestqueue Getqueue () {return queue;}}

This can interact with the activity. The ability to cancel the operation of the network request (via tag) when the activity exits, the following can be achieved:

@Overrideprotected void OnStop () {//TODO auto-generated Method Stubvolleyapplication.getqueue (). Cancelall ("Strreqget "); Super.onstop ();}


Use the application label in the Androidmainfist.xml file to register just the volleylication:

<application        android:allowbackup= "true"        android:icon= "@drawable/ic_launcher"      <span style= " Color: #ff0000; " >  android:name= "com.example.volleyHttp.volleyApplication" </span>        android:label= "@string/app_ Name "        android:theme=" @style/apptheme ">        <activity            android:name=". Mainactivity "            android:label=" @string/app_name ">            <intent-filter>                <action android:name=" Android.intent.action.MAIN "/>                <category android:name=" Android.intent.category.LAUNCHER "/>            </intent-filter>        </activity>    </application>

Don't forget to join the network permissions!


4.StringRequest Get and Post methods

4.1 Get Operation

(1) Instantiating Stringrequest objects

(2) Set parameters: Request method, URL address, successful return call. The failed return call.

(3) Set tag for the request. Join in the request queue just now!

private void Strrequest_get () {stringrequest request = new Stringrequest (Method.get,httppath.getsharedifo (1), new Listener<string> () {@Overridepublic void Onresponse (String response) {//TODO auto-generated method Stubtoast.maketext (Getapplicationcontext (), Response,toast.length_short). Show (); Tv.settext (response);}, new Response.errorlistener () {@Overridepublic void Onerrorresponse (volleyerror error) {Toast.maketext ( Getapplicationcontext (), Error.getmessage (), Toast.length_short). Show ();}); Request.settag ("Strreqget"); <span style= "color: #ff0000;" >volleyapplication.getqueue (). Add (request); </span>}

4.2 Post Operation

(1) Instantiating Stringrequest objects

(2) Set parameters: Request method, URL address, successful return call, failed return call;

(3) The parameter setting for post submission: Override the Getparams method. Returns the Map collection and invokes itself voluntarily;

(4) Request to set tag, add to the request queue just now!


/** * 01.2 String requset post submit data */private void Strrequest_post () {stringrequest stringrequest=new stringrequest (Method . Post,httppath.getsharedifo_post (), new listener<string> () {@Overridepublic void Onresponse (String response) {// Successful return Data Tv.settext (response),}},new Response.errorlistener () {@Overridepublic void Onerrorresponse (volleyerror error) {//Error Toast.maketext (Getapplicationcontext (), Error.getmessage (), Toast.length_short). Show ();}) {@Overrideprotected map<string, string> getparams () throws Authfailureerror {//Post to submit an override, and commit the parameters yourself Map<stri Ng,string> map=new hashmap<string, string> (); Map.put ("id", "2"); return map;}}; Stringrequest.settag ("Strpost"); Volleyapplication.getqueue (). Add (Stringrequest);


5.JsonObjectRequest Get and Post methods

5.1 Get Method

(1) Instantiating Jsonobjectrequest objects

(2) Set the number of parameters: Request method, URL address. The parameter jsonrequest is null (due to a GET request), and a successful return call is made. A failed return call;

(3) Set the tag to the request and add it to the request queue.

(4) When the request succeeds, it is returned directly to the Jsonobject object. can be used directly


/** * 02.jsonobjectRequert GET request */private void Jsonrequest_get () {jsonobjectrequest objectrequest=new Jsonobjectrequest (Method.get,httppath.getsharedifo (1), Null,new listener<jsonobject> () {@Overridepublic void Onresponse (jsonobject response) {//directly JSON parse try {jsonobject jsonobject=new jsonobject (response.getstring ("Data")); Tv.settext (jsonobject.getstring ("note")); catch (Jsonexception e) {//TODO auto-generated catch Blocktv.settext (E.getmessage ());}}},new Response.errorlistener () {@Overridepublic void Onerrorresponse (volleyerror error) {//request failed to return information Tv.settext (Error.getmessage ());}}); O Bjectrequest.settag ("Jsonrequest"); Volleyapplication.getqueue (). Add (Objectrequest);

5.2 Post Method

(1) Instantiating Jsonobjectrequest objects

(2) Set the number of parameters: Request method, URL address, parameter jsonrequest , successful return call, failed return call.

(3) Request parameter setting: Implement post submission parameter setting via JSONOBEJCT (see Demo sample code)

(4) Set tag for the request. Join to the request queue just now.

(5) After the request is successful. Direct return to Jsonobject object, can be used directly

/** * 02.2 Jsonobjectrequest POST Method request */private void Jsonrequest_post () {<span style= "color: #ff0000;"   >//Package request Parameters </span> Jsonobject jsonstr=new jsonobject ();      try {jsonstr.put ("id", "2"),} catch (Jsonexception E1) {//TODO auto-generated catch Blocke1.printstacktrace ();} Jsonobjectrequest jsonobjectrequest=new jsonobjectrequest (Method.post,httppath.getsharedifo_post (), JSONSTR, new Listener<jsonobject> () {@Overridepublic void Onresponse (jsonobject response) {//TODO auto-generated method Stubjsonobject jsonobject;try {jsonobject = new Jsonobject (response.getstring ("Data")); Tv.settext ( Jsonobject.getstring ("note"));} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}},new Response.errorlistener () {@ overridepublic void Onerrorresponse (volleyerror error) {//TODO auto-generated method Stubtv.settext (Error.getmessage (   ));}});   Jsonobjectrequest.settag ("Jsonpost");        Volleyapplication.getqueue (). Add (Jsonobjectrequest); } 


6.JsonArrayRequest

I'm not a burden anymore, just like Jsonobjectresquest, only the Jsonarray type is returned.

7. Note

Requestqueue request queue when initializing, be sure to register in the Application tab of the Android configuration file.

Use of the time. Note Import package problem, Errorlistener must be response.errorlistener;

Android-volley Network communication Framework (Stringrequest &amp; Jsonobjectrequest)

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.