Android--using Volley+fastjson to read the network interface in a new thread get weather information

Source: Internet
Author: User
<span id="Label3"></p><p><p><br></p></p><p><p><br></p></p><span style="font-family:FangSong_GB2312;font-size:24px;"><span style="font-family:FangSong_GB2312;font-size:24px;">one, about Volley</span></span><p><p><br></p></p><p><p><span style="font-family:FangSong_GB2312;">in <span style="font-size:18px;">fact, initially for the network data access, I did not expect to use the framework, using HttpURLConnection or HttpGet or httppost can be achieved. But why? Why I</span> has to use volley?</span></p></p><p><p><br></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><strong>before Volley:</strong></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"></span></p></p><pre name="code" class="java"><span style="font-size:12px;">Class Httpurlconnection_post extends thread{@Overridepublic void run () {//set The requested path string Strurl= "/http/ api.qingyunke.com/api.php ";////UTF-8 encode the requested parameter and convert it to a byte array =try {String params=" key= "+urlencoder.encode (" free "," UTF-8 ") +" appid= "+urlencoder.encode (" 0 "," UTF-8 ") +" msg= "+urlencoder.encode (" weather Meizhou "," UTF-8 "); byte[] postdata= Params.getbytes ();//create a URL object url url=new url (strurl);//open a httpurlconnection connection httpurlconnection urlconn= ( Httpurlconnection) Url.openconnection ();//set The time of connection timeout urlconn.setdooutput (true);//when using a post request, The setting cannot use the cache urlconn.setusecaches (false);//set the request as a POST request Urlconn.setrequestmethod ("post"); Urlconn.setinstancefollowredirects (true);//configuration request Content-typeurlconn.setrequestproperty ("content-type", " Application/x-www-form-urlencode ");//perform Connection Operation Urlconn.connect ();//send request Parameters DataOutputStream Dos=new DataOutputStream ( Urlconn.getoutputstream ());d os.write (postdata);d os.flush ();d os.close ();//if The request succeeds by reading the connected data stream, gets the returned data if ( Urlconn.getresponsecode () ==200) {//display inputstreamreader ISR = new INPUTSTREAMREader (urlconn.getinputstream (), "utf-8"); int i; String strresult = ""; Read while ((i = Isr.read ())! =-1) {strresult = strresult + (char) i; } isr.close (); textview= (textview) Findviewbyid (r.id.textview1); Textview.settext (strresult); Displayed in Textview}else{textview.settext (urlconn.getresponsecode ());//display in textview}} catch (Exception e) {//TODO Auto-generated Catch Blocke.printstacktrace ();}} }</span></pre><p><p></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><br></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;">For the above code, I can only say that will be used.</span></p></p><p><p><br><span style="font-family:FangSong_GB2312;font-size:18px;"></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><br></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><strong>Volley source:</strong></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;">Volley is Google's launch of the Android Asynchronous network request framework and picture loading Framework. Released at the Google I/O 2013 Conference.</span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;">From the name of the origin and map of countless rapid rockets can be seen volley characteristics: especially suitable for small data volume, communication frequent network Operation. (individuals think that the vast majority of network operations in Android apps belong to this type).</span></p></p><p id="1-2-volley-"><p id="1-2-volley-"><span style="font-size:18px;"></span></p></p><p><p><span style="font-size:18px;"><span style="font-family:FangSong_GB2312;"><strong>Main Features:</strong></span></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;">(1). Strong Extensibility. Most of the volley are based on the interface design, which is highly configurable.<br>(2). to a certain extent in line with the Http specification, including the return responsecode (2xx, 3xx, 4xx, 5xx) processing, request Header processing, caching mechanism Support. and supports retry and priority Definitions.<br>(3). the default Android2.3 and above based on the httpurlconnection,2.3 below based on the HttpClient implementation, the difference between the merits and demerits in the <code>4.2.1 Volley</code> specific Introduction.<br>(4). provides a simple image loading Tool.<br></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><br></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;">Based on the fact that it has so many advantages, and more official orthodoxy, is an extension and optimization on the basis of the original network access class, so we use it to read and write data from the Network.</span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><br></span></p></p><span style="font-family:FangSong_GB2312;"><span style="font-family:FangSong_GB2312;"> <span style="font-size:24px;">two, using Fastjson</span><br></span></span><p><p><span style="font-family:FangSong_GB2312;"><br></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;">Wirelessly data is based on a lightweight and efficient format JSON as a carrier. so, in Android development, There's a lot of code, and we're going to convert the JSON strings and objects or collections into Code.</span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><br></span></p></p><p><p><span style="font-size:18px;"> <span style="font-family:FangSong_GB2312;">We can use the traditional jsonobject or jsonarray:</span> </span></p></p><p><p><span style="font-size:10px;"></span></p></p><pre name="code" class="java"><pre name="code" class="java"><span style="font-family:Microsoft YaHei;font-size:12px;">Create an object Jsonobject person=new jsonobject (); Create an Array object Jsonarray phone=new Jsonarray (); Phone.put ("123445"); Try {person.put ("name", "lhc");p erson.put ("age", 100);//create An object jsonobject address=new jsonobject (); address.put (" Country "," "china"), address.put ("province", "hebei");p erson.put ("address", address),//json text parsing jsonobject object= New Jsonobject (person.tostring ()); Jsonarray Array=object.getjsonarray ("phone"); String phonenum= (string) array.get (0); String name=object.getstring ("name"); int age=object.getint ("age"); Jsonobject Object1=object.getjsonobject ("address"); String country=object1.getstring ("country"); String province=object1.getstring ("province");} Catch (jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}</span></pre></pre><span style="font-size:18px;"><span style="font-size:18px;"><br></span></span><p><p><span style="font-size:18px;"><span style="font-family:FangSong_GB2312;"><br></span></span></p></p><p><p><span style="font-size:18px;"><span style="font-family:FangSong_GB2312;">But this approach is not efficient, so we can use Fastjson or Jackjson to implement the simple operation of this process.</span></span></p></p><p><p></p></p><p><p><br></p></p><span style="font-size:24px;"><span style="font-size:24px;">third, about Android open new thread and why to use asynchronous processing message class</span></span><br><p><p></p></p><p style="margin:0in;font-size:10.5pt"><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">the threading model of the Android system is a single-threaded model, if</span></span><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;">UI</span></span><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">threads to access or update only in the</span></span><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;">UI</span></span><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">the view class that is updated in the thread will report an Exception. But many time-consuming operations cannot be put in</span></span><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;">UI</span></span><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">threads, We can only be on the main</span> thread</span><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;">Start</span></span><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">a new thread, and then put the new thread into our network access,</span></span><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;">IO</span></span><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;"><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">Access and other Operations. </span></span></p><p style="margin:0in;font-size:10.5pt"><p style="margin:0in;font-size:10.5pt"><span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">But when we get to the data, because in the non-</span> <span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;">UI</span> <span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">updates are not allowed in threads</span> <span lang="en-US" style="font-family:FangSong_GB2312;font-size:18px;">UI</span> <span lang="zh-CN" style="font-family:FangSong_GB2312;font-size:18px;">component view, So we're going to use the asynchronous processing of the message class to notify the main thread and complete the operation of updating the VIEW. </span></p></p><p style="margin: 0in; font-size: 10.5pt;"><p style="margin: 0in; font-size: 10.5pt;"><span style="font-family:FangSong_GB2312;font-size:18px;"></span></p></p><span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:24px;">three, Simple Demo</span></span></span><p><p><br></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;">The first is the entity class that corresponds to my json:</span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"></span></p></p><pre name="code" class="java"><pre name="code" class="java"><span style="font-size:12px;">Package Com.example.demoproject;public class Weatherinfo {private string result;//the result of the request private string content;// The returned content public String GetResult () {return result;} public void Setresult (String Result) {this.result = result;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;}}</span></pre></pre><br><span style="font-size:18px;"><span style="font-size:18px;"> <span style="font-family:FangSong_GB2312;">original Json:</span> </span></span><p><p></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"></span></p></p><pre name="code" class="javascript"><pre name="code" class="javascript">{ "result": 0, "content": "★ Beijing weather {br} haze, 18 ℃, Northeast Wind 2 level {br}★ three days forecast {br}[10 month 06th] daytime: haze, 25 ℃, No continuous wind direction; night: fog, 15 ℃, no continuous direction {br}[ October 07] daytime: yin, 25 ℃, No continuous wind direction; night: sunny, 13 ℃, North Wind {br}[10 month 08th] daytime: sunny, 19 ℃, North wind; night: cloudy, 9 ℃, no continuous wind "}</pre></pre><span style="font-size:18px;"><span style="font-size:18px;"><br><span style="font-family:FangSong_GB2312;">then refer to the jar package of volley and Fastjson:</span> </span></span><p><p></p></p><p><p><br></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"></span></p></p><p><p><br></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;">To configure access permissions for a network in Androidmanifest.xml:</span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><br></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:12px;"></span></p></p><pre name="code" class="html"><pre name="code" class="html"></pre></pre><p><p></p></p><p><p><span style="font-size:18px;"><br></span></p></p><p><p><span style="font-size:18px;">Code in Activity:</span></p></p><p><p><span style="font-size:18px;"><br></span></p></p><p><p></p></p><pre name="code" class="java"><span style="font-size:12px;">Package Com.example.demoproject;import Java.io.unsupportedencodingexception;import Java.net.urlencoder;import Com.alibaba.fastjson.json;import Com.android.volley.requestqueue;import Com.android.volley.response;import Com.android.volley.volleyerror;import Com.android.volley.request.method;import Com.android.volley.toolbox.stringrequest;import Com.android.volley.toolbox.volley;import android.os.Bundle; Import Android.os.handler;import Android.os.message;import Android.support.v7.app.actionbaractivity;import Android.widget.textview;public class Mainactivity extends actionbaractivity {private static final int msg_success = 0;//received Get weather information Successful identification private static final int msg_failure = 1;//obtain Weather information failure identification Private TextView TextView; /* * This gets the requestqueue is a request queue object, * It can cache all HTTP requests, and then make these requests in parallel with a certain algorithm. * Requestqueue internal design is very suitable for high concurrency, * so we do not have to create a Requestqueue object for every HTTP request, * This is a very waste of resources, Basically creating a Requestqueue object in every activity that needs to interact with the network is Sufficient. * */private Requestqueue mqueue; Handler private Handler Mhand for updating the UI threadLer=new Handler () {///this method executes @overridepublic void Handlemessage (Message msg) {switch (msg.what) {case msg_success in the UI thread: Weatherinfo weather= (weatherinfo) msg.obj; Get message information Textview.settext (weather.getcontent ()); break;case MSG_FAILURE:textView.setText ("get information failed, please retry later"); }; @Overrideprotected void onCreate (Bundle Savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( savedinstancestate); setcontentview (r.layout.activity_main); textview= (textView) Findviewbyid (R.id.textview1); Mqueue=volley.newrequestqueue (mainactivity.this); New Thread (new weathertest ()). start ();//read The data in a new thread and bind}/* * Read weather data using a fresh thread * Weather Interface example: * http://api.qingyunke.com/api.php? key=free&appid=0&msg= Weather Beijing * */class Weathertest implements runnable{@Overridepublic void run () {String strurl= ' http://api.qingyunke.com/api.php?key=free&appid=0&msg= ";//the Address of the request data string strcity=" "; try {/* * * Note: the parameters in the volley must be encoded, otherwise garbled problems will occur * */strcity=urlencoder.encode ("weather beijing", "UTF-8");} Catch (unsupportedencodingexception e) {//TODO AUto-generated Catch Blocke.printstacktrace ();} strurl+=strcity;/* * Send HTTP requests using Stringrequest objects encapsulated in Volley * Stringrequest requires three Parameters: * 0, method to get Data * 1, URL address of destination server * 2, the server responds with a successful callback * 3, the server responds with a failed callback * */stringrequest stringrequest = new Stringrequest (method.get,strurl, New Response.listener<string> () {@Override public void Onresponse (String Response) {/* * Successfully obtained data after processing */ Weatherinfo weatherinfo=null; Convert JSON string to object Weatherinfo=json.parseobject (response.tostring (), weatherinfo.class); Bind data procedure Mhandler.obtainmessage (msg_success,weatherinfo). Sendtotarge T (); }}, New Response.errorlistener () {@Override public void Onerrorresponse (volleyerror error) {//read failed processing Mhandler.obtainmessage (msg_failure). Sendtotarget (); } }); Mqueue.add (stringrequest); Add the request to the request queue}}}</span></pre><br><p><p></p></p><p><p><strong>  </strong><span style="font-size:18px;"><strong>          </strong></span></p></p><p><p><span style="font-size:18px;"><strong><br></strong></span></p></p><p><p><span style="font-size:18px;"><br><strong></strong></span></p></p><p><p><span style="font-size:18px;"><strong><br></strong></span></p></p><p><p><span style="font-size:18px;"><strong>JRKJ Overall framework is being perfected, Welcome to add!</strong><br></span></p></p><p><p><br></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><br></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"><br></span></p></p><p><p><span style="font-family:FangSong_GB2312;font-size:18px;"></span><span style="font-size:18px;"><br></span></p></p><p><p><br></p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android--using Volley+fastjson to read the network interface in a new thread get weather information</p></p></span>
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.