Android 天气预报【解析XML / Json文件(2种方式:手动解析、Gson库解析)】
生活随笔
收集整理的這篇文章主要介紹了
Android 天气预报【解析XML / Json文件(2种方式:手动解析、Gson库解析)】
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
源碼 [工程文件]: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目錄找到相應的文件。
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 {//調(diào)用工具類[傳參:inputStream流]List<WeatherInfo> weatherInfos = WeatherService.getInfosFromXML(inputStream);list = new ArrayList<Map<String, String>>();//存儲天氣信息的集合//循環(huán)讀取weatherInfos中的每一條數(shù)據(jù)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;/*** 創(chuàng)建天氣的實體類*/ 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、初始化解析器,第一個參數(shù)代表包含xml的數(shù)據(jù)parser.setInput(is, "utf-8");//流、編碼List<WeatherInfo> weatherInfos = null;WeatherInfo weatherInfo = null;//3、得到當前事件的類型int type = parser.getEventType();//4、不到文件的結(jié)尾,就一直解析。END_DOCUMENT: 文檔結(jié)束標簽while (type != XmlPullParser.END_DOCUMENT) {//5、具體判斷一下解析的是什么標簽(開始標簽or結(jié)束標簽)。switch (type) {//一個節(jié)點的開始標簽case XmlPullParser.START_TAG://代表 解析 開始標簽//解析到全局開始的標簽 infos 根節(jié)點if ("infos".equals(parser.getName())) {//parser.getName(): 拿到當前標簽的名字weatherInfos = new ArrayList<WeatherInfo>();//創(chuàng)建集合對象} 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節(jié)點中的內(nèi)容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;//一個節(jié)點結(jié)束的標簽case XmlPullParser.END_TAG://一個城市的信息處理完畢,city的結(jié)束標簽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);//把流中的數(shù)據(jù)讀到緩沖區(qū)中//通過buffer數(shù)組構(gòu)造新字符串。讀取json數(shù)據(jù)String json = new String(buffer, "utf-8");//使用gson庫解析JSON數(shù)據(jù)Gson gson = new Gson();//定義類型(定義一個什么樣的類型)【TypeToken-->想要的類型】Type listType = new TypeToken<List<WeatherInfo>>() {}.getType();//解析。兩個參數(shù)(json串、返回類型)List<WeatherInfo> weatherInfos = gson.fromJson(json, listType);return weatherInfos;}/*** 解析json文件返回天氣信息的集合* [* {"temp":"20℃/30℃","weather":"晴轉(zhuǎn)多云","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;//字節(jié)流-->字符串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); // []將字符串轉(zhuǎn)為json數(shù)組;{}大括號開始---jsonObjectfor (int i = 0; i < array.length(); i++) { // 對數(shù)組進行遍歷,對所有對象進行處理---循環(huán)3次JSONObject object = array.optJSONObject(i); // 官方建議【可以處理異常】獲取對象//JSONObject object=array.getJSONObject(i); // 作用與上一行相同info = new WeatherInfo();info.setWind(object.optString("wind")); // 根據(jù)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 :
weather2.json :
更改 MainActivity.java 文件 :
總結(jié)
以上是生活随笔為你收集整理的Android 天气预报【解析XML / Json文件(2种方式:手动解析、Gson库解析)】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vscode配置问题
- 下一篇: Android 数据显示控件(ListV