最近在做一个天气预报的Widget,通过google提供的api可以查询全世界的天气情况,这篇文章主要讲述如何通过Android的JSON获取城市的经纬度,程序很简单。稍后我将demo供来此博客的朋友。废话少说,且看下文:

设计如下:通过JsonDemoActivity输入国家简称,跳转到CityListActivity(用来显示城市列表),点击需要查询城市返回天气信息。在JsonDemoActivity显示天气信息,Utils是解析天气和城市的主要工具类。

知识点:

1、多个Activity之间传递数据(一般Activity之间用来传递的是基本的数据类型,比如说String,int,boolean等),其中有个方法,可以用来传递对象,我就是讲城市和天气信息写成相应的JavaBean,用来传递的;

2、Json数据解析,获取城市;

3、解析Xml数据,获取天气;

4、部分Google API的讲解;

5、解析图片。

(关于google wearher api 的说明在:http://tsov.net/weather-queries-using-the-google-weather-api/

结构如下:

以下是效果图:

(国家列表)

(城市列表)

(天气情况)

主要代码(代码不做多余解释自己看吧):

一、获取数据

view plain copy to clipboard print ? ·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
  1. /**
  2. *得到数据
  3. *@paramargs
  4. *@return
  5. */
  6. publicfinalstaticInputStreamgetStream(Stringargs){
  7. InputStreamstream=null;
  8. DefaultHttpClientclient=newDefaultHttpClient();
  9. HttpGetget=newHttpGet(args);
  10. try{
  11. HttpResponseresponse=client.execute(get);
  12. if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
  13. HttpEntityentity=response.getEntity();
  14. stream=entity.getContent();
  15. }
  16. returnstream;
  17. }catch(Exceptione){
  18. e.printStackTrace();
  19. returnstream;
  20. }
  21. }
/** * 得到数据 * @param args * @return */ public final static InputStream getStream(String args) { InputStream stream = null; DefaultHttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(args); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); stream = entity.getContent(); } return stream; } catch (Exception e) { e.printStackTrace(); return stream; } }

二、解析天气

view plain copy to clipboard print ? ·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
  1. /**
  2. *通过解析xml数据得到天气信息
  3. *@paramargs
  4. *@return
  5. */
  6. publicstaticWeatherBeangetCurrentWeather(Stringargs){
  7. Documentdocument=null;
  8. try{
  9. DocumentBuilderbuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
  10. document=builder.parse(newInputSource(getStream(args)));
  11. }catch(ParserConfigurationExceptione){
  12. e.printStackTrace();
  13. }catch(FactoryConfigurationErrore){
  14. e.printStackTrace();
  15. }catch(SAXExceptione){
  16. e.printStackTrace();
  17. }catch(IOExceptione){
  18. e.printStackTrace();
  19. }
  20. //当天天气
  21. WeatherBeanweather=newWeatherBean();
  22. NodeListnodeList=document.getElementsByTagName("current_conditions").item(0).getChildNodes();//当前天气
  23. Stringcondition=nodeList.item(0).getAttributes().item(0).getNodeValue();//天气情况
  24. StringtempF=nodeList.item(1).getAttributes().item(0).getNodeValue();//华氏度
  25. StringtempC=nodeList.item(2).getAttributes().item(0).getNodeValue();//摄氏度
  26. Stringhumidity=nodeList.item(3).getAttributes().item(0).getNodeValue();//湿度
  27. StringimgUrl=nodeList.item(4).getAttributes().item(0).getNodeValue();//天气图片
  28. StringwindCondition=nodeList.item(5).getAttributes().item(0).getNodeValue();//风速描述
  29. weather.setCondition(condition);
  30. weather.setTempF(Integer.parseInt(tempF));
  31. weather.setTempC(Integer.parseInt(tempC));
  32. weather.setHumidity(humidity);
  33. //weather.setIcon(reDrawable(imgUrl));//解析图片
  34. weather.setWindCondition(windCondition);
  35. returnweather;
  36. }
/** * 通过解析xml数据得到天气信息 * @param args * @return */ public static WeatherBean getCurrentWeather(String args){ Document document = null; try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); document = builder.parse(new InputSource(getStream(args))); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (FactoryConfigurationError e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 当天天气 WeatherBean weather= new WeatherBean(); NodeList nodeList = document.getElementsByTagName("current_conditions").item(0).getChildNodes(); // 当前天气 String condition = nodeList.item(0).getAttributes().item(0).getNodeValue(); // 天气情况 String tempF = nodeList.item(1).getAttributes().item(0).getNodeValue(); // 华氏度 String tempC = nodeList.item(2).getAttributes().item(0).getNodeValue(); // 摄氏度 String humidity = nodeList.item(3).getAttributes().item(0).getNodeValue(); // 湿度 String imgUrl = nodeList.item(4).getAttributes().item(0).getNodeValue(); // 天气图片 String windCondition = nodeList.item(5).getAttributes().item(0).getNodeValue(); // 风速描述 weather.setCondition(condition); weather.setTempF(Integer.parseInt(tempF)); weather.setTempC(Integer.parseInt(tempC)); weather.setHumidity(humidity); // weather.setIcon(reDrawable(imgUrl)); // 解析图片 weather.setWindCondition(windCondition); return weather; }

三、Google返回的Json数据,用Json解析城市

view plain copy to clipboard print ?
  1. /**
  2. *通过Android提供的Json方式解析城市信息
  3. *@paramcountryCode
  4. *@return
  5. */
  6. publicstaticList<CityBean>getCityInfos(StringcountryCode){
  7. List<CityBean>cityList=newArrayList<CityBean>();
  8. //
  9. StringBuildersBuilder=newStringBuilder();
  10. BufferedReaderbReader=newBufferedReader(newInputStreamReader(getStream(countryCode)));
  11. try{
  12. for(Strings=bReader.readLine();s!=null;s=bReader.readLine()){
  13. sBuilder.append(s);
  14. }
  15. }catch(IOExceptione){
  16. e.printStackTrace();
  17. }
  18. try{
  19. JSONObjectjsonObject=newJSONObject(sBuilder.toString());
  20. JSONArrayjsonArray=jsonObject.getJSONArray("cities");
  21. for(inti=0;i<jsonArray.length();i++){
  22. CityBeancityBean=newCityBean();
  23. JSONObjectjsonObj=(JSONObject)jsonArray.opt(i);
  24. cityBean.setCityName(jsonObj.getString("name"));
  25. cityBean.setLat(jsonObj.getLong("lat"));
  26. cityBean.setLon(jsonObj.getLong("lon"));
  27. cityList.add(cityBean);
  28. Log.i(TAG,"name="+jsonObj.getString("name")+";lat="+jsonObj.getLong("lat")+";lon="+jsonObj.getLong("lon"));
  29. }
  30. }catch(JSONExceptione){
  31. e.printStackTrace();
  32. }
  33. returncityList;
  34. }
/** * 通过Android 提供的Json方式解析城市信息 * @param countryCode * @return */ public static List<CityBean> getCityInfos(String countryCode) { List<CityBean> cityList = new ArrayList<CityBean>(); // StringBuilder sBuilder = new StringBuilder(); BufferedReader bReader = new BufferedReader(new InputStreamReader(getStream(countryCode))); try { for (String s = bReader.readLine(); s != null; s = bReader.readLine()) { sBuilder.append(s); } } catch (IOException e) { e.printStackTrace(); } try { JSONObject jsonObject = new JSONObject(sBuilder.toString()); JSONArray jsonArray = jsonObject.getJSONArray("cities"); for (int i = 0; i < jsonArray.length(); i++) { CityBean cityBean = new CityBean(); JSONObject jsonObj = (JSONObject) jsonArray.opt(i); cityBean.setCityName(jsonObj.getString("name")); cityBean.setLat(jsonObj.getLong("lat")); cityBean.setLon(jsonObj.getLong("lon")); cityList.add(cityBean); Log.i(TAG, "name="+jsonObj.getString("name")+";lat="+jsonObj.getLong("lat")+";lon="+jsonObj.getLong("lon")); } } catch (JSONException e) { e.printStackTrace(); } return cityList; }

我这里只是通过经纬度查询城市天气预报。也可以通过其他的方式,具体的请看上面那个链接。

Demo下载地址:http://download.csdn.net/source/3339328

更多相关文章

  1. “罗永浩抖音首秀”销售数据的可视化大屏是怎么做出来的呢?
  2. Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
  3. 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
  4. 增加android 拥有root权限的服务
  5. Android利用mediacodec进行视频H264编码解码播放
  6. Android去除TextView文本中的默认内边距
  7. Android大图片裁剪终极解决方案(上:原理分析)
  8. Android(安卓)LitePal的简单使用
  9. Android录音上————AudioRecord实现录音功能

随机推荐

  1. Flink Forward 201904 PPT资料下载
  2. 【OpenYurt 深度解析】边缘网关缓存能力
  3. 将scp传输速度发挥到极致
  4. 摩杜云:大数据时代,最优配比CDN的重要性
  5. 网站收录不给关键词,这几个问题检查你的网
  6. 表格、表单以及简单的地图显示(iframe)
  7. 2021-03-31:给定一个数组arr,给定一个值v。
  8. 具有调节变量的中介效应程序和数据, 独家
  9. 【论文】Awesome RelationExtractionPape
  10. 基于特定实体的文本情感分类总结(PART III