源码 [工程文件]:https://gitee.com/lwx001/Weather

XML :


activity_main.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/weather"tools:context=".MainActivity"><TextViewandroid:id="@+id/tv_city"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignEnd="@+id/tv_weather"android:layout_alignRight="@+id/tv_weather"android:layout_alignParentTop="true"android:layout_marginTop="39dp"android:text="上海"android:textSize="50sp" /><ImageViewandroid:id="@+id/iv_icon"android:layout_width="70dp"android:layout_height="70dp"android:layout_below="@+id/tv_city"android:layout_alignStart="@+id/ll_btn"android:layout_alignLeft="@+id/ll_btn"android:layout_marginStart="44dp"android:layout_marginLeft="44dp"android:layout_marginTop="42dp"android:paddingBottom="5dp"android:src="@mipmap/ic_launcher" /><TextViewandroid:id="@+id/tv_weather"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/iv_icon"android:layout_alignRight="@+id/iv_icon"android:layout_marginTop="18dp"android:layout_marginRight="15dp"android:gravity="center"android:text="多云"android:textSize="18sp" /><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignTop="@+id/iv_icon"android:layout_marginStart="39dp"android:layout_marginLeft="39dp"android:layout_toEndOf="@+id/iv_icon"android:layout_toRightOf="@+id/iv_icon"android:gravity="center"android:orientation="vertical"><TextViewandroid:id="@+id/tv_temp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:gravity="center_vertical"android:text="-7℃"android:textSize="22sp" /><TextViewandroid:id="@+id/tv_wind"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="风力:3级"android:textSize="18sp" /><TextViewandroid:id="@+id/tv_pm"android:layout_width="73dp"android:layout_height="wrap_content"android:text="pm"android:textSize="18sp" /></LinearLayout><LinearLayoutandroid:id="@+id/ll_btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_centerHorizontal="true"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_bj"android:layout_width="wrap_content"android:layout_height="match_parent"android:text="北京" /><Buttonandroid:id="@+id/btn_sh"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="上海" /><Buttonandroid:id="@+id/btn_gz"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="广州" /></LinearLayout>
</RelativeLayout>

weather1.xml【res\raw目录下】 :
raw中的文件会被自动解析、编译。通过raw目录找到相应的文件。

<?xml version="1.0" encoding="utf-8"?>
<infos><city id="sh"><temp>20℃/30℃</temp><weather>晴天多云</weather><name>上海</name><pm>80</pm><wind>1级</wind></city><city id="bj"><temp>26℃/32℃</temp><weather>晴天</weather><name>北京</name><pm>98</pm><wind>3级</wind></city><city id="gz"><temp>15℃/24℃</temp><weather>多云</weather><name>广州</name><pm>30</pm><wind>5级</wind></city>
</infos>

MainActivity.java :

package cn.lwx.weather;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private TextView tvCity;private TextView tvWeather;private TextView tvTemp;private TextView tvWind;private TextView tvPm;private ImageView ivIcon;private List<Map<String, String>> list;//存储天气信息的集合private Map<String, String> map;private String temp, weather, name, pm, wind;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//raw中的文件会被自动解析、编译。通过raw目录找到相应的文件//1、初始化文本控件initView();//2、读取解析weather1.xml文件信息 / getResources()得到资源文件InputStream inputStream = getResources().openRawResource(R.raw.weather1);try {//调用工具类[传参:inputStream流]List<WeatherInfo> weatherInfos = WeatherService.getInfosFromXML(inputStream);list = new ArrayList<Map<String, String>>();//存储天气信息的集合//循环读取weatherInfos中的每一条数据for (WeatherInfo info : weatherInfos) {map = new HashMap<String, String>();map.put("temp", info.getTemp());map.put("weather", info.getWeather());map.put("name", info.getName());map.put("pm", info.getPm());map.put("wind", info.getWind());list.add(map);}} catch (Exception e) {e.printStackTrace();}//自定义getMap()方法,显示天气信息到文本控件中,默认显示北京的天气getMap(1, R.drawable.sun);}private void initView() {tvCity = (TextView) findViewById(R.id.tv_city);tvWeather = (TextView) findViewById(R.id.tv_weather);tvTemp = (TextView) findViewById(R.id.tv_temp);tvWind = (TextView) findViewById(R.id.tv_wind);tvPm = (TextView) findViewById(R.id.tv_pm);ivIcon = (ImageView) findViewById(R.id.iv_icon);//展示图片findViewById(R.id.btn_sh).setOnClickListener(this);//设置点击findViewById(R.id.btn_bj).setOnClickListener(this);findViewById(R.id.btn_gz).setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btn_sh://点击上海getMap(0, R.drawable.cloud_sun);break;case R.id.btn_bj://点击北京getMap(1, R.drawable.sun);break;case R.id.btn_gz://点击广州getMap(2, R.drawable.clouds);break;}}//自定义getMap()方法,将城市天气信息分条展示到界面上,默认显示北京天气private void getMap(int number, int iconNumber) {Map<String, String> cityMap = list.get(number);temp = cityMap.get("temp");weather = cityMap.get("weather");name = cityMap.get("name");pm = cityMap.get("pm");wind = cityMap.get("wind");tvCity.setText(name);tvWeather.setText(weather);tvTemp.setText("" + temp);tvWind.setText("风力  : " + wind);tvPm.setText("pm: " + pm);ivIcon.setImageResource(iconNumber);}
}

WeatherInfo.java :

package cn.lwx.weather;/*** 创建天气的实体类*/
public class WeatherInfo {private String id;private String temp;private String weather;private String name;private String pm;private String wind;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getTemp() {return temp;}public void setTemp(String temp) {this.temp = temp;}public String getWeather() {return weather;}public void setWeather(String weather) {this.weather = weather;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPm() {return pm;}public void setPm(String pm) {this.pm = pm;}public String getWind() {return wind;}public void setWind(String wind) {this.wind = wind;}}

WeatherService.java :

package cn.lwx.weather;import android.util.Xml;import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;/*** 解析天气的工具类*/
public class WeatherService {//解析xml文件返回天气信息的集合 [存储解析信息的集合] 接收InputStream流public static List<WeatherInfo> getInfosFromXML(InputStream is) throws Exception {//1、获取pull解析器XmlPullParser parser = Xml.newPullParser();//工具类//2、初始化解析器,第一个参数代表包含xml的数据parser.setInput(is, "utf-8");//流、编码List<WeatherInfo> weatherInfos = null;WeatherInfo weatherInfo = null;//3、得到当前事件的类型int type = parser.getEventType();//4、不到文件的结尾,就一直解析。END_DOCUMENT: 文档结束标签while (type != XmlPullParser.END_DOCUMENT) {//5、具体判断一下解析的是什么标签(开始标签or结束标签)。switch (type) {//一个节点的开始标签case XmlPullParser.START_TAG://代表 解析 开始标签//解析到全局开始的标签 infos 根节点if ("infos".equals(parser.getName())) {//parser.getName(): 拿到当前标签的名字weatherInfos = new ArrayList<WeatherInfo>();//创建集合对象} else if ("city".equals(parser.getName())) {weatherInfo = new WeatherInfo();//初始化weatherInfo的信息String idStr = parser.getAttributeValue(0);//获取weather1.xml文件中city的id值weatherInfo.setId(idStr);} else if ("temp".equals(parser.getName())) {//parset.nextText()得到该tag节点中的内容String temp = parser.nextText();weatherInfo.setTemp(temp);} else if ("weather".equals(parser.getName())) {String weather = parser.nextText();weatherInfo.setWeather(weather);} else if ("name".equals(parser.getName())) {String name = parser.nextText();weatherInfo.setName(name);} else if ("pm".equals(parser.getName())) {String pm = parser.nextText();weatherInfo.setPm(pm);} else if ("wind".equals(parser.getName())) {String wind = parser.nextText();weatherInfo.setWind(wind);}break;//一个节点结束的标签case XmlPullParser.END_TAG://一个城市的信息处理完毕,city的结束标签if ("city".equals(parser.getName())) {weatherInfos.add(weatherInfo);//把bean对象加到集合中weatherInfo = null;}break;}type = parser.next();//赋值:解析后的事件类型-下一个事件的类型}return weatherInfos;}//json比xml更轻量、更易于阅读//解析json文件返回天气信息的集合【使用封装好的jar包】public static List<WeatherInfo> getInfosFromJson(InputStream is) throws IOException {byte[] buffer = new byte[is.available()];is.read(buffer);//把流中的数据读到缓冲区中//通过buffer数组构造新字符串。读取json数据String json = new String(buffer, "utf-8");//使用gson库解析JSON数据Gson gson = new Gson();//定义类型(定义一个什么样的类型)【TypeToken-->想要的类型】Type listType = new TypeToken<List<WeatherInfo>>() {}.getType();//解析。两个参数(json串、返回类型)List<WeatherInfo> weatherInfos = gson.fromJson(json, listType);return weatherInfos;}/*** 解析json文件返回天气信息的集合* [* {"temp":"20℃/30℃","weather":"晴转多云","name":"上海","pm":"80","wind":"1级"},* {"temp":"15℃/24℃","weather":"晴","name":"北京","pm":"98","wind":"3级"},* {"temp":"26℃/32℃","weather":"多云","name":"广州","pm":"30","wind":"2级"}* ]** @param is 输入流* @return 城市天气列表* @throws Exception*/public static List<WeatherInfo> getInfosFromJson2(InputStream is) throws Exception {List<WeatherInfo> weatherInfos = new ArrayList<>();WeatherInfo info;//字节流-->字符串byte[] buffer = new byte[is.available()];is.read(buffer);String json = new String(buffer, "utf-8");/*** 1.[]  JSONArray array=new JSONArray(json);* 2.{}  JSONObject obj=new JSONObject(json);* 3.optJSONArray、optJSONObject* optString*/JSONArray array = new JSONArray(json); // []将字符串转为json数组;{}大括号开始---jsonObjectfor (int i = 0; i < array.length(); i++) { // 对数组进行遍历,对所有对象进行处理---循环3次JSONObject object = array.optJSONObject(i); // 官方建议【可以处理异常】获取对象//JSONObject object=array.getJSONObject(i); // 作用与上一行相同info = new WeatherInfo();info.setWind(object.optString("wind")); // 根据key,获取具体属性info.setTemp(object.optString("temp"));info.setName(object.optString("name"));info.setPm(object.optString("pm"));info.setWeather(object.getString("weather"));weatherInfos.add(info);//info = null;}return weatherInfos;}}

JSON :

添加库文件 ( json ):


若添加gson包失败,可更改build.gradle文件,然后重启项目:

build.gradle :

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {repositories {maven{url 'http://maven.aliyun.com/nexus/content/groups/public/'}maven { url "https://jitpack.io" }google()//jcenter()}dependencies {classpath 'com.android.tools.build:gradle:3.6.1'// NOTE: Do not place your application dependencies here; they belong// in the individual module build.gradle files}
}allprojects {repositories {maven{url 'http://maven.aliyun.com/nexus/content/groups/public/'}maven { url "https://jitpack.io" }google()//jcenter()}
}task clean(type: Delete) {delete rootProject.buildDir
}


weather2.json :

[{"temp":"20℃/30℃","weather":"晴转多云","name":"上海","pm":"80","wind":"1级"},{"temp":"15℃/24℃","weather":"晴","name":"北京","pm":"98","wind":"3级"},{"temp":"26℃/32℃","weather":"多云","name":"广州","pm":"30","wind":"2级"}
]

更改 MainActivity.java 文件 :

Android 天气预报【解析XML / Json文件(2种方式:手动解析、Gson库解析)】相关推荐

  1. android最大json,Android:解析大型JSON文件

    我正在创建一个Android应用程序,该应用程序应该将Json从文件或网址解析为jsonarray和jsonobjects. 问题是,我的JSON是3.3 MB,当我使用一个简单的代码,如下所示:(现 ...

  2. IDEA Java解析GeoJson.json文件

    IDEA Java解析GeoJson.json文件 一.遇到的问题 1. 无法导入成功 2. org.geotools.StyleFactory is not an ImageIO SPI class ...

  3. Php流式 大文件,如何使用PHP解析XML大文件

    如果使用 PHP 解析 XML 的话,那么常见的选择有如下几种:DOM.SimpleXML.XMLReader.如果要解析 XML 大文件的话,那么首先要排除的是 DOM,因为使用 DOM 的话,需要 ...

  4. 在线解析xml,json数据的网址

    在线解析xml,json数据的网址 https://www.sojson.com/yasuoyihang.html

  5. 解析超大JSON文件

    解析超大JSON文件 1.需求 最近项目中需要将一个一个大于50G的JSON文件导入到ES中,试过普通的按行读取文件和JSONReader流读取文件,由于json文件实在过于庞大,都不能解决问题. 2 ...

  6. json文件两种读取方式

    json文件两种读取方式 这是一段两个人的对话标注抄本 [{"start_time": {"original": "0:00:00.611000&qu ...

  7. android获取自定义属性,android 自定义控件中获取属性的三种方式(转)

    第一种方法,直接设置属性值,通过attrs.getAttributeResourceValue拿到这个属性值. (1)在xml文件中设置属性值 android:layout_width="f ...

  8. php 生成复杂json数据,生成json的几种方式

    这里是修真院后端小课堂,每篇分享文从 [背景介绍][知识剖析][常见问题][解决方案][编码实战][扩展思考][更多讨论][参考文献] 八个方面深度解析后端知识/技能,本篇分享的是: [生成json的 ...

  9. 返回ajax有几种方式,java ajax返回 Json 的 几种方式

    方式 1. : 自写代码转 Json 需要  HttpHttpServletRequest request  HttpServletResponse response 后台 : @RequestMap ...

最新文章

  1. Constant expression required
  2. 有源汇上下界最小费用可行流 ---- P4043 [AHOI2014/JSOI2014]支线剧情(模板)
  3. python基础知识面试题-干货满满--亲身经历的 Python 面试题
  4. mysql 清理host文件_如何删除mysql 数据库里面的host
  5. 八、给小白看的第一篇Python基础教程
  6. Sword STL之map效率问题
  7. Android实现简单的检测手机自由落体关闭屏幕
  8. php 后退按钮事件,php – 后退按钮的会话问题
  9. python内置函数详解总结篇_Python内置函数详解——总结篇
  10. 垂直柱状图(洛谷-P1598 )
  11. 还没使用过Web Worker,推荐一款开源工具Workerize,快速上手
  12. php使用excel表格数据处理,php上传excel表格并获取数据
  13. intersystem-M语言基础语法
  14. 扫雷可以用计算机,windows扫雷
  15. 分区助手是什么?(博主推荐)(图文详解)
  16. 屠龙之技 作者:长铗
  17. 手把手教你制作油管上30万播放的动态登录页面效果
  18. 爪爪博士:小奶猫感冒发烧怎么降温才有效
  19. vncviewer退出全屏
  20. 用计算机专业怼人,专业示范,教你如何用所学专业知识“怼人”

热门文章

  1. android 实现磨砂效果_Android 5.0 下毛玻璃(磨砂)效果如何实现?
  2. 单调不减序列查询第一个大于等于_[力扣84,85] 单调栈
  3. 深度学习篇| keras入门(一)
  4. java 读 xml_Java读写XML代码示例
  5. React  学习第二天 2018-07-21
  6. Vue.js 学习视频和书籍【推荐】
  7. Vue 学习第五天 学习笔记
  8. ACM-ICPC 2018 焦作赛区网络预赛
  9. 洛谷P3919可持久化线段树
  10. Android轮播图实现图片圆角,Android开发实现图片圆角的方法