Android Combat--Weather forecast (Api+json analysis)

Source: Internet
Author: User
Tags sunrise time

Learning Android For some time, should improve their actual combat ability, do some simple demo. Below we introduce how to use the network API to realize the weather forecast function, mainly involves how to use the API to obtain the network data, the network data return is generally the JSON format, here also involves the JSON parsing problem, these are the relatively basic problem, should be mastered.

First find the API you want in HTTP://APISTORE.BAIDU.COM/?QQ-PF-TO=PCQQ.C2C, here we choose http://apistore.baidu.com/astore/serviceinfo/ 1798.html, there is an introduction to the API on the webpage:

interface Address:Http://apistore.baidu.com/microservice/weather

Request Method: GET

Request Parameters:
Name of parameter type must fill in parameter Position Description Default Value
Citypinyin String Is Urlparam City Pinyin Beijing
Sample Request:
Http://apistore.baidu.com/microservice/weather?citypinyin=beijing
JSON Returns an example:
{errnum:0,errmsg: "Success", Retdata: {   City: "Beijing",//urban   Pinyin: "Beijing",//city Pinyin   Citycode: "101010100", c4/>//City Code   Date: "15-02-11",//Date   time: "11:00",//Published   postcode: "100000",//Zip   longitude:116.391,/ /Longitude   latitude:39.904,//Dimension   altitude: "33",//elevation   weather: "Clear",  //weather conditions   Temp: "10",//air temperature   L_ TMP: "4",//Minimum temperature   h_tmp: "10",//maximum temperature   WD: "No continuous wind Direction",//Wind Direction   WS: "Breeze (<10m/h)",//Wind   Sunrise: "07:12", Sunrise Time   Sunset: "17:44"//Sunset Time  }    }

Here's the layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical "&G    T <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:minHeig ht= "30DP" android:text= "Weather Forecast" android:textsize= "26DP"/> <linearlayout android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:minheight= "30DP" android:orientation= "Hori            Zontal "> <edittext android:id=" @+id/myedit "android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_weight= "1111"/> <button Andro            Id:id= "@+id/searchweather" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_weight= "1" android:text= "Query Weather"/> </LinearLayout> <linearlayout android:layout_width= "fi Ll_parent "android:layout_height=" wrap_content "android:minheight=" 30DP "android:orientation=" horizon Tal "> <textview android:layout_width=" wrap_content "android:layout_height=" Wrap_conten T "android:layout_weight=" 1 "android:text=" City: "/> <textview android:id=" @+i D/city "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android: layout_weight= "1"/> </LinearLayout> <linearlayout android:layout_width= "Fill_parent" Android oid:layout_height= "Wrap_content" android:minheight= "30DP" android:orientation= "Horizontal" > <T Extview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:       layout_weight= "1"     android:text= "weather:"/> <textview android:id= "@+id/weather" android:layout_width= "WR Ap_content "android:layout_height=" Wrap_content "android:layout_weight=" 1 "/> </linearlayou t> <linearlayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" and roid:minheight= "30DP" android:orientation= "horizontal" > <textview android:layout_width= "WR Ap_content "android:layout_height=" Wrap_content "android:layout_weight=" 1 "android:text="            Real-time temperature: "/> <textview android:id=" @+id/temp "android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_weight= "1"/> </LinearLayout> <linearl Ayout android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:minheight= "30DP "Android:orientation= "Horizontal" > <textview android:layout_width= "wrap_content" android:layout_height            = "Wrap_content" android:layout_weight= "1" android:text= "Low temperature:"/> <textview            Android:id= "@+id/h_temp" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_weight= "1"/> </LinearLayout> <linearlayout android:layout_width= "Fill_pa Rent "android:layout_height=" wrap_content "android:minheight=" 30DP "android:orientation=" Horizontal "            > <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_weight= "1" android:text= "High temperature:"/> <textview android:id= "@+id/l _temp "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:l  ayout_weight= "1"/>  </LinearLayout></LinearLayout> 


The following connection tool class:

Package Org.lxh.demo;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStreamReader; Import Java.net.httpurlconnection;import Java.net.url;public class Httpdownloader {private URL url = null;/** * download file based on URL , as long as the content in this file is text, the return value of the function is the content of the text 1. Create a URL Object * 2. Through the URL object, create a HttpURLConnection object 3. Get InputStream 4. Read data from InputStream * * @param urlstr * @return */public string Download (string urlstr) {StringBuffer sb = new Stringbuffe R (); String line = null; BufferedReader buffer = null;try {url = new URL (urlstr); HttpURLConnection urlconn = (httpurlconnection) url.openconnection (); Urlconn.setrequestmethod ("GET"); Urlconn.setconnecttimeout (8000); Urlconn.setreadtimeout (8000); buffer = new BufferedReader (New InputStreamReader ( Urlconn.getinputstream ()); (line = Buffer.readline ())! = null) {Sb.append (line)}} catch (Exception e) {e.printstacktrace ();} finally {try {buffer.close ();} catch (IOException e) {e.printstacktrace ()}} return sb.tostring ();}}


To parse this JSON data after getting the return string:

Package Org.lxh.demo;import Java.util.arraylist;import Java.util.hashmap;import java.util.list;import java.util.Map ; Import Org.json.jsonobject;public class Util {public list<map<string, object>> getinformation (String jonstring) throws Exception {Jsonobject jsonobject = new Jsonobject (jonstring); Jsonobject retdata = Jsonobject.getjsonobject ("Retdata"); List<map<string, object>> all = new arraylist<map<string, object>> (); map<string, object> map = new hashmap<string, object> (), Map.put ("CityName", Retdata.optstring ("City")); Map.put ("Weather", retdata.optstring ("Weather")), Map.put ("Temp", retdata.optstring ("temp")), Map.put ("L_temp", Retdata.optstring ("L_tmp")), Map.put ("H_temp", Retdata.optstring ("h_tmp")); All.add (map); return all;}}


The following activity program:

Package Org.lxh.demo;import Java.util.iterator;import Java.util.list;import java.util.map;import Android.annotation.suppresslint;import Android.app.activity;import Android.app.progressdialog;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;public class Main extends Activity {private EditText Citynameedittext;private Button searchweatherbutton;private TextView citynamettextview;private TextView Weahtertextview;private TextView temptextview;private TextView h_temptextview;private TextView L_temptextview; String jonstring; ProgressDialog progressdialog;private static final int SET = 1; @SuppressLint ("Handlerleak") private Handler Handler = new H Andler () {@Overridepublic void Handlemessage (Message msg) {switch (msg.what) {case Set:util Util = new Util (); try {list&lt ; Map<string, object>> all = Util.getinformation (msg.obj.toString ()); iterator<map<string, object>> Iterator = All.iterator (); while (Iterator.hasnext ()) {map<string, object> Map = Iterator.next (); LOG.D ("Weather", map.get ("Weather"). ToString ()); Citynamettextview.settext (Map.get ("CityName"). ToString ()); Weahtertextview.settext (Map.get ("Weather"). ToString ()); Temptextview.settext (Map.get ("temp"). ToString ()); H_ Temptextview.settext (Map.get ("L_temp"). ToString ()); L_temptextview.settext (Map.get ("H_temp"). ToString ());}} catch (Exception e) {e.printstacktrace ();} finally {}break;}}}; public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);//life cycle Method Super.setcontentview ( R.layout.main); Set the layout manager to use Citynameedittext = (EditText) Findviewbyid (r.id.myedit); Searchweatherbutton = (Button) Findviewbyid ( R.id.searchweather); Citynamettextview = (TextView) Findviewbyid (r.id.city); Weahtertextview = (TextView) Findviewbyid (r.id.weather); Temptextview = (TextView) Findviewbyid (r.id.temp); H_temptextview = (TextView) Findviewbyid (r.id.h_temp); L_temptextview = (TextView) Findviewbyid (r.id.l_temp); Searchweatherbutton.setonclicklistener (New Onclicklistener () {public void OnClick (View v) {New Thread (new Newthread ()) . Start (); LOG.D ("Key", "Success");});} Private class Newthread implements Runnable {public void run () {String address = "http://apistore.baidu.com/microservice/ Weather?citypinyin= "+ citynameedittext.gettext (). toString (); Httpdownloader Httpdownloader = new Httpdownloader (); String jonstring = httpdownloader.download (address); Message msg = Main.this.handler.obtainMessage (Main.set, jonstring); Main.this.handler.sendMessage (msg);}}}


To run an instance effect:

DEMO: http://download.csdn.net/detail/yayun0516/8705675

This example only resolves a few data as an example, if you need additional data, you can add it yourself, the principle is the same. Play with your imagination!

At last:

My application: http://openbox.mobilem.360.cn/index/d/sid/2966005

http://android.myapp.com/myapp/detail.htm?apkName=com.yayun.gitlearning

Welcome to download, there are problems and more communication!

Android Combat--Weather forecast (Api+json analysis)

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.