Android实战--天气预报(API+JSON解析)

 学习安卓有一段时间了,应该提高自己的实战能力,做一些简单的Demo。下面我们介绍一下如何利用网络API实现天气预报功能,主要涉及到如何利用API获得网络数据,网络数据返回一般是JSON格式,这里又涉及到JSON的解析问题,这些都是比较基础的问题,应该予以掌握。

首先在http://apistore.baidu.com/?qq-pf-to=pcqq.c2c找到你想要的API,这里我们选择http://apistore.baidu.com/astore/serviceinfo/1798.html,网页里有关于API的介绍:

接口地址:http://apistore.baidu.com/microservice/weather

请求方法:GET

请求参数: 参数名 类型 必填 参数位置 描述 默认值
citypinyin string urlParam 城市拼音 beijing
请求示例:
http://apistore.baidu.com/microservice/weather?citypinyin=beijing
JSON返回示例:
{
errNum: 0,
errMsg: "success",
retData: {
   city: "北京", //城市
   pinyin: "beijing", //城市拼音
   citycode: "101010100",  //城市编码	
   date: "15-02-11", //日期
   time: "11:00", //发布时间
   postCode: "100000", //邮编
   longitude: 116.391, //经度
   latitude: 39.904, //维度
   altitude: "33", //海拔	
   weather: "晴",  //天气情况
   temp: "10", //气温
   l_tmp: "-4", //最低气温
   h_tmp: "10", //最高气温
   WD: "无持续风向",	 //风向
   WS: "微风(<10m/h)", //风力
   sunrise: "07:12", //日出时间
   sunset: "17:44" //日落时间
  }    
}

下面搞一下布局文件:

[html]  view plain copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:minHeight="30dp"  
  11.         android:text="天气预报"  
  12.         android:textSize="26dp" />  
  13.   
  14.     <LinearLayout  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:minHeight="30dp"  
  18.         android:orientation="horizontal" >  
  19.   
  20.         <EditText  
  21.             android:id="@+id/myedit"  
  22.             android:layout_width="wrap_content"  
  23.             android:layout_height="wrap_content"  
  24.             android:layout_weight="1111" />  
  25.   
  26.         <Button  
  27.             android:id="@+id/searchweather"  
  28.             android:layout_width="wrap_content"  
  29.             android:layout_height="wrap_content"  
  30.             android:layout_weight="1"  
  31.             android:text="查询天气 " />  
  32.     </LinearLayout>  
  33.   
  34.     <LinearLayout  
  35.         android:layout_width="fill_parent"  
  36.         android:layout_height="wrap_content"  
  37.         android:minHeight="30dp"  
  38.         android:orientation="horizontal" >  
  39.   
  40.         <TextView  
  41.             android:layout_width="wrap_content"  
  42.             android:layout_height="wrap_content"  
  43.             android:layout_weight="1"  
  44.             android:text="城市:" />  
  45.   
  46.         <TextView  
  47.             android:id="@+id/city"  
  48.             android:layout_width="wrap_content"  
  49.             android:layout_height="wrap_content"  
  50.             android:layout_weight="1" />  
  51.     </LinearLayout>  
  52.   
  53.     <LinearLayout  
  54.         android:layout_width="fill_parent"  
  55.         android:layout_height="wrap_content"  
  56.         android:minHeight="30dp"  
  57.         android:orientation="horizontal" >  
  58.   
  59.         <TextView  
  60.             android:layout_width="wrap_content"  
  61.             android:layout_height="wrap_content"  
  62.             android:layout_weight="1"  
  63.             android:text="天气:" />  
  64.   
  65.         <TextView  
  66.             android:id="@+id/weather"  
  67.             android:layout_width="wrap_content"  
  68.             android:layout_height="wrap_content"  
  69.             android:layout_weight="1" />  
  70.     </LinearLayout>  
  71.   
  72.     <LinearLayout  
  73.         android:layout_width="fill_parent"  
  74.         android:layout_height="wrap_content"  
  75.         android:minHeight="30dp"  
  76.         android:orientation="horizontal" >  
  77.   
  78.         <TextView  
  79.             android:layout_width="wrap_content"  
  80.             android:layout_height="wrap_content"  
  81.             android:layout_weight="1"  
  82.             android:text="实时气温:" />  
  83.   
  84.         <TextView  
  85.             android:id="@+id/temp"  
  86.             android:layout_width="wrap_content"  
  87.             android:layout_height="wrap_content"  
  88.             android:layout_weight="1" />  
  89.     </LinearLayout>  
  90.   
  91.     <LinearLayout  
  92.         android:layout_width="fill_parent"  
  93.         android:layout_height="wrap_content"  
  94.         android:minHeight="30dp"  
  95.         android:orientation="horizontal" >  
  96.   
  97.         <TextView  
  98.             android:layout_width="wrap_content"  
  99.             android:layout_height="wrap_content"  
  100.             android:layout_weight="1"  
  101.             android:text="最低气温:" />  
  102.   
  103.         <TextView  
  104.             android:id="@+id/h_temp"  
  105.             android:layout_width="wrap_content"  
  106.             android:layout_height="wrap_content"  
  107.             android:layout_weight="1" />  
  108.     </LinearLayout>  
  109.   
  110.     <LinearLayout  
  111.         android:layout_width="fill_parent"  
  112.         android:layout_height="wrap_content"  
  113.         android:minHeight="30dp"  
  114.         android:orientation="horizontal" >  
  115.   
  116.         <TextView  
  117.             android:layout_width="wrap_content"  
  118.             android:layout_height="wrap_content"  
  119.             android:layout_weight="1"  
  120.             android:text="最高气温:" />  
  121.   
  122.         <TextView  
  123.             android:id="@+id/l_temp"  
  124.             android:layout_width="wrap_content"  
  125.             android:layout_height="wrap_content"  
  126.             android:layout_weight="1" />  
  127.     </LinearLayout>  
  128.   
  129. </LinearLayout>  


下面连接工具类:

[java]  view plain copy
 
  1. package org.lxh.demo;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. public class HttpDownloader {  
  10.   
  11.     private URL url = null;  
  12.   
  13.     /** 
  14.      * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容 1.创建一个URL对象 
  15.      * 2.通过URL对象,创建一个HttpURLConnection对象 3.得到InputStream 4.从InputStream当中读取数据 
  16.      *  
  17.      * @param urlStr 
  18.      * @return 
  19.      */  
  20.     public String download(String urlStr) {  
  21.         StringBuffer sb = new StringBuffer();  
  22.         String line = null;  
  23.         BufferedReader buffer = null;  
  24.         try {  
  25.             url = new URL(urlStr);  
  26.             HttpURLConnection urlConn = (HttpURLConnection) url  
  27.                     .openConnection();  
  28.             urlConn.setRequestMethod("GET");  
  29.             urlConn.setConnectTimeout(8000);  
  30.             urlConn.setReadTimeout(8000);  
  31.             buffer = new BufferedReader(new InputStreamReader(  
  32.                     urlConn.getInputStream()));  
  33.             while ((line = buffer.readLine()) != null) {  
  34.                 sb.append(line);  
  35.             }  
  36.   
  37.         } catch (Exception e) {  
  38.             e.printStackTrace();  
  39.         } finally {  
  40.             try {  
  41.                 buffer.close();  
  42.             } catch (IOException e) {  
  43.                 e.printStackTrace();  
  44.             }  
  45.         }  
  46.         return sb.toString();  
  47.     }  
  48. }  


获取返回字符串之后要对此JSON数据进行解析:

[java]  view plain copy
 
  1. package org.lxh.demo;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.json.JSONObject;  
  9.   
  10. public class Util {  
  11.   
  12.     public List<Map<String, Object>> getInformation(String jonString)  
  13.             throws Exception {  
  14.   
  15.         JSONObject jsonObject = new JSONObject(jonString);  
  16.         JSONObject retData = jsonObject.getJSONObject("retData");  
  17.         List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();  
  18.         Map<String, Object> map = new HashMap<String, Object>();  
  19.         map.put("cityName", retData.optString("city"));  
  20.         map.put("weather", retData.optString("weather"));  
  21.         map.put("temp", retData.optString("temp"));  
  22.         map.put("l_temp", retData.optString("l_tmp"));  
  23.         map.put("h_temp", retData.optString("h_tmp"));  
  24.         all.add(map);  
  25.   
  26.         return all;  
  27.   
  28.     }  
  29.   
  30. }  


下面Activity程序:

[java]  view plain copy
 
  1. package org.lxh.demo;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import android.annotation.SuppressLint;  
  7. import android.app.Activity;  
  8. import android.app.ProgressDialog;  
  9. import android.os.Bundle;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.util.Log;  
  13. import android.view.View;  
  14. import android.view.View.OnClickListener;  
  15. import android.widget.Button;  
  16. import android.widget.EditText;  
  17. import android.widget.TextView;  
  18.   
  19. public class Main extends Activity {  
  20.     private EditText citynameEditText;  
  21.     private Button searchWeatherButton;  
  22.     private TextView citynametTextView;  
  23.     private TextView weahterTextView;  
  24.     private TextView tempTextView;  
  25.     private TextView h_tempTextView;  
  26.     private TextView l_tempTextView;  
  27.     String jonString;  
  28.     ProgressDialog progressDialog;  
  29.     private static final int SET = 1;  
  30.     @SuppressLint("HandlerLeak")  
  31.     private Handler handler = new Handler() {  
  32.   
  33.         @Override  
  34.         public void handleMessage(Message msg) {  
  35.             switch (msg.what) {  
  36.             case SET:  
  37.                 Util util = new Util();  
  38.                 try {  
  39.                     List<Map<String, Object>> all = util  
  40.                             .getInformation(msg.obj.toString());  
  41.                     Iterator<Map<String, Object>> iterator = all.iterator();  
  42.                     while (iterator.hasNext()) {  
  43.                         Map<String, Object> map = iterator.next();  
  44.                         Log.d("天气", map.get("weather").toString());  
  45.                         citynametTextView.setText(map.get("cityName")  
  46.                                 .toString());  
  47.                         weahterTextView.setText(map.get("weather").toString());  
  48.                         tempTextView.setText(map.get("temp").toString());  
  49.                         h_tempTextView.setText(map.get("l_temp").toString());  
  50.                         l_tempTextView.setText(map.get("h_temp").toString());  
  51.   
  52.                     }  
  53.                       
  54.   
  55.                 } catch (Exception e) {  
  56.                     e.printStackTrace();  
  57.                 } finally {  
  58.   
  59.                 }  
  60.                 break;  
  61.   
  62.             }  
  63.   
  64.         }  
  65.   
  66.     };  
  67.   
  68.     public void onCreate(Bundle savedInstanceState) {  
  69.         super.onCreate(savedInstanceState); // 生命周期方法  
  70.         super.setContentView(R.layout.main); // 设置要使用的布局管理器  
  71.         citynameEditText = (EditText) findViewById(R.id.myedit);  
  72.         searchWeatherButton = (Button) findViewById(R.id.searchweather);  
  73.         citynametTextView = (TextView) findViewById(R.id.city);  
  74.         weahterTextView = (TextView) findViewById(R.id.weather);  
  75.         tempTextView = (TextView) findViewById(R.id.temp);  
  76.         h_tempTextView = (TextView) findViewById(R.id.h_temp);  
  77.         l_tempTextView = (TextView) findViewById(R.id.l_temp);  
  78.           
  79.           
  80.           
  81.         searchWeatherButton.setOnClickListener(new OnClickListener() {  
  82.               
  83.             public void onClick(View v) {  
  84.                 new Thread(new NewThread()).start();  
  85.                 Log.d("按键""Success");  
  86.                   
  87.                   
  88.             }  
  89.         });  
  90.     }  
  91.   
  92.     private class NewThread implements Runnable {  
  93.   
  94.         public void run() {  
  95.               
  96.             String address = "http://apistore.baidu.com/microservice/weather?citypinyin="  
  97.                     + citynameEditText.getText().toString();  
  98.   
  99.             HttpDownloader httpDownloader = new HttpDownloader();  
  100.             String jonString = httpDownloader.download(address);  
  101.             Message msg = Main.this.handler  
  102.                     .obtainMessage(Main.SET, jonString);  
  103.             Main.this.handler.sendMessage(msg);  
  104.   
  105.         }  
  106.   
  107.     }  
  108.   
  109.       
  110.   Android实战--天气预报(API+JSON解析)
  111. }  


运行实例效果:

猜你喜欢

转载自p98989695q.iteye.com/blog/2225285