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" //日落时间 } }
下面搞一下布局文件:
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; /** * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容 1.创建一个URL对象 * 2.通过URL对象,创建一个HttpURLConnection对象 3.得到InputStream 4.从InputStream当中读取数据 * * @param urlStr * @return */ public String download(String urlStr) { StringBuffer sb = new StringBuffer(); 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())); while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { buffer.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
获取返回字符串之后要对此JSON数据进行解析:
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; } }
下面Activity程序:
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 Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SET: Util util = new Util(); try { List<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("天气", 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); // 生命周期方法 super.setContentView(R.layout.main); // 设置要使用的布局管理器 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("按键", "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); } } Android实战--天气预报(API+JSON解析) }
运行实例效果:
相关推荐
染血白衣 2020-11-16
SAMXIE 2020-11-04
一个智障 2020-11-15
学习web前端 2020-11-09
yiranpiaoluo 2020-11-04
lxhuang 2020-11-03
88274956 2020-11-03
82387067 2020-11-03
huangliuyu00 2020-10-29
sichenglain 2020-10-27
Dayer 2020-10-27
小马的学习笔记 2020-10-23
liuweiITlove 2020-10-14
kjyiyi 2020-10-10
fanjunjaden 2020-10-09
zhyue 2020-09-28
huangliuyu00 2020-09-24
88397813 2020-09-23
jyj0 2020-09-21