Get weather information with JSON

Source: Internet
Author: User


Weather forecast information is obtained using JSON, there are a lot of resources on the Internet, source code. Because it involves a lot of weather information, including humidity, travel advice, etc., as well as a resource bundle that joins all city codes. In order to practiced hand understand the principle of JSON. I only get the highest temperature, lowest temperature, city name of the honest city.

My layout is through a button to get the city name, the highest temperature, the lowest temperature. MAIN.XNL code such as the following

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <textview android:id= "@+id/textview1" android:layout_width= "Wrap_content" Android:layout_h eight= "Wrap_content" android:text= "City Name:"/> <edittext android:id= "@+id/tx_cityname" Android     : layout_width= "match_parent" android:layout_height= "Wrap_content" android:ems= "ten" > </EditText> <textview android:id= "@+id/textview2" android:layout_width= "Wrap_content" Android:layout_heigh t= "wrap_content" android:text= "Maximum temperature:"/> <edittext android:id= "@+id/tx_height" android:layou T_width= "Match_parent" android:layout_height= "Wrap_content" android:ems= "ten"/> <textview an Droid:id= "@+id/textview3" anDroid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Minimum temperature:"/> <Edi Ttext android:id= "@+id/tx_low" android:layout_width= "match_parent" android:layout_height= "Wrap_conten T "android:ems=" ten "/> <button android:id=" @+id/button_refresh "android:layout_width=" Wrap_cont Ent "android:layout_height=" wrap_content "android:gravity=" center "android:text=" get real-time weather information "> &L T;/button></linearlayout>

This project contains 2 Java files, each of which is a Wheatherlck.java and Wheatherinfo.java file. Wheatherlck.java code such as the following

Package Com.hiden.weatherdemo;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.httpstatus;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.util.entityutils;import Org.json.jsonexception;import Org.json.jsonobject;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.app.activity;import Android.content.intent;import Android.util.Log;import Android.view.keyevent;import Android.view.menu;import Android.view.view;import Android.widget.Button;import Android.widget.edittext;import Android.widget.imageview;import Android.widget.textview;public class WeatherLck Extends Activity {//Create three Global text box object EditText tx_cityname,tx_height,tx_low;private String city_str= "Chengdu";Button Button_refresh; @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.main);//Get text box in Layout tx_cityname= (EditText) This.findviewbyid (R.id.tx_cityname); Tx_cityname.settext (CITY_STR); tx_height= (EditText) This.findviewbyid (r.id.tx_height); tx_low= (EditText) This.findviewbyid (R.id.tx_low); button_refresh= (Button) Findviewbyid (R.id.button_refresh); Button_refresh.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method Stubif (V==button_refresh) {refresh (CITY_STR);}}); * Get HTTP// m.weather.com.cn/data/101091106.html above Data * 101091106 is the city code, above I have changed the city code, removed the empty line, in the format of UTF-8 * each time just to execute a thread, and then increase the main thread recycling * @param city_str * @throws jsonexception * @throws Exception * @throws clientprotocolexception */private thread thread ;p rivate Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {switch (msg.what) {case 1:jsonobject weather = (jsonobject) msg.obj; Refreshui (weather); try {thread.join ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} break;}}};/ * Cannot request a network * thread in the main thread without a while loop is only executed once, Suppose an overflow may not send a message * @param city_str */private void Requestweather (final String city_str) {thread = new thread (new Runnable () {@O verridepublic void Run () {//TODO auto-generated method stubstring url= "http://www.weather.com.cn/data/cityinfo/ 101270101.html "; HttpClient client = new Defaulthttpclient (); HttpGet httpget = new HttpGet (URL); HttpResponse response; String Sbuf = null;try {response = Client.execute (HttpGet); Httpentity httpentity = response.getentity (), if (httpentity! = null) {BufferedReader BR = new BufferedReader (new InputStreamReader (Httpentity.getcontent (), "Utf-8")); sbuf = Br.readline ();} Jsonobject object = new Jsonobject (SBUF); Jsonobject data = (jsonobject) object.getjsonobject ("Weatherinfo");//log.i (TAG, data.tostring ()); Message msg = new Message (); msg.what = 1;msg.obj = Data;handler.sendmessage (msg);} catch (Clientprotocolexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO Auto-generated catch Blocke.printstacktrace ();} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}); Thread.Start ();} protected void Refresh (String city_str) {requestweather (CITY_STR);} private void Refreshui (Jsonobject jsonobject) {Jsonobject jsondata = Jsonobject;try{tx_cityname.settext ( Jsondata.getstring ("City"));//obtain High temperature data Tx_height.settext (jsondata.getstring ("Temp1"));//obtain cryogenic data Tx_low.settext ( Jsondata.getstring ("Temp2"));} catch (Exception e) {e.printstacktrace ();}}}


Wheatherinfo.java code such as the following:

Package Com.hiden.weatherdemo.ui;public class Weatherinfo {String city = ""; String Temp1 = ""; String temp2 = "";//Starling Wind Central public String getcity () {return city;} public void Setcity (String city) {this.city = city;} @Overridepublic String toString () {return "Weatherinfo [city=" + City + ", temp1=" + temp1+ ", temp2=" + Temp2 + "]";} Public String GetTemp1 () {return temp1;} public void SetTemp1 (String temp) {this.temp1 = temp;} Public String getTemp2 () {return temp2;} public void setTemp2 (String temp) {this.temp2 = temp;}}
Click button to get the highest and lowest temperatures to Chengdu, such as the following:

Of course, we can make more specific according to their own needs, for example, to join the next 5 days of weather, positioning, to join the focus on the city and other functions. More online resources, we can practice more.



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.