Android天氣預(yù)報(bào)之基于HttpGet對象解析天氣數(shù)據(jù)的方法
本文實(shí)例所述為Android天氣預(yù)報(bào)之解析天氣數(shù)據(jù)的代碼,可實(shí)現(xiàn)獲取HttpGet對象讀取天氣網(wǎng)站天氣數(shù)據(jù),并從數(shù)據(jù)中解析出天氣數(shù)據(jù),比如溫度、溫度、風(fēng)力、風(fēng)向、未來幾天天氣趨勢、當(dāng)天天氣狀況、空氣污染指數(shù)等信息,還包括了調(diào)用對應(yīng)的圖片或天氣動(dòng)畫文件,對于開發(fā)android天氣預(yù)報(bào)程序的可以參考本文實(shí)例。
具體功能代碼如下:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.lmw.weather.MyApp;
import org.lmw.weather.entity.WeatherEntity;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
/**
* 解析天氣數(shù)據(jù)
* @author Dave
*/
public class WeatherData {
private Activity activity;
private FinalHttp fh;
public static String def_weather_key="def_weather";
public WeatherData(Activity activity) {
this.activity = activity;
fh = new FinalHttp();
fh.configTimeout(1000 * 3);
}
public void getData(final String cityId,final Handler hd) {
StringBuffer sb_url = new StringBuffer();
sb_url.append("http://0.qnweather.duapp.com/weather.php?uri=");
sb_url.append("http://m.weather.com.cn/data/");
sb_url.append(cityId);
sb_url.append(".html");
final Message msg=new Message();
fh.get(sb_url.toString(), new AjaxCallBack() {
@Override
public void onSuccess(Object t) {
super.onSuccess(t);
MySharedPreferences.writeMessage(activity, "def_weather",t.toString());
msg.what=0;
msg.obj=parseJson(t.toString());
hd.sendMessage(msg);
}
@Override
public void onFailure(Throwable t, int errorNo, String strMsg) {
super.onFailure(t, errorNo, strMsg);
System.out.println("-------errorNo---------"+errorNo);
msg.what=-1;
msg.arg1=errorNo;
msg.obj=MySharedPreferences.readMessage(activity, def_weather_key, "");
hd.sendMessage(msg);
}
});
}
private String connServerForResult(String strUrl) {
// 獲取HttpGet對象
HttpGet httpRequest = new HttpGet(strUrl);
String strResult = "";
try {
// HttpClient對象
HttpClient httpClient = new DefaultHttpClient();
// 獲得HttpResponse對象
HttpResponse httpResponse = httpClient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的數(shù)據(jù)
strResult = EntityUtils.toString(httpResponse.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("rresult" + strResult);
return strResult; // 返回結(jié)果
}
// 數(shù)據(jù)解析
private WeatherEntity parseJson(String strResult) {
WeatherEntity weather = null;
try {
JSONObject jsonObj = new JSONObject(strResult.replace("℃", "°"))
.getJSONObject("weatherinfo");
weather = new WeatherEntity();
int ftime = jsonObj.getInt("fchh"); // 更新時(shí)間(整點(diǎn))【更新時(shí)間確定temp屬于哪天】
int temp = 0; // 偏移
if (ftime >= 18 || ftime < 8) {
weather.setNight(true);
temp = 1;
}
MyApp.week = jsonObj.getString("week");// 今天星期幾
weather.setCity(jsonObj.getString("city")); // 城市
weather.setComfortable(jsonObj.getString("index")); // 舒適度
weather.setRefreshDate(getDate()); // 更新日期
weather.setRefreshTime(getTime()); // 更新時(shí)間
weather.setRefreshWeek(getWeek()); // 更新星期
weather.setPicIndex(jsonObj.getInt("img1")); // 當(dāng)天天氣圖片編號
List<Integer> topPic = new ArrayList<Integer>(); // 最高溫時(shí)的圖片編號
if (temp == 1) {
topPic.add(getSavePic(activity));
} else {
topPic.add(getJsonPic(jsonObj, "img", 1 + temp));
savePic(activity, topPic.get(0));
}
topPic.add(getJsonPic(jsonObj, "img", 3 - temp));
topPic.add(getJsonPic(jsonObj, "img", 5 - temp));
topPic.add(getJsonPic(jsonObj, "img", 7 - temp));
weather.setTopPic(topPic);
List<Integer> lowPic = new ArrayList<Integer>(); // 最低溫時(shí)的圖片編號
lowPic.add(getJsonPic(jsonObj, "img", 2 - temp));
lowPic.add(getJsonPic(jsonObj, "img", 4 - temp));
lowPic.add(getJsonPic(jsonObj, "img", 6 - temp));
lowPic.add(getJsonPic(jsonObj, "img", 8 - temp));
weather.setLowPic(lowPic);
// ---------------------------以上為獲取圖片編號,暫且不管----------------------------------------------------------------------
List<String> tempList = new ArrayList<String>(); // 未來五天溫度(第一個(gè)是今天)
tempList.add(jsonObj.getString("temp1"));
tempList.add(jsonObj.getString("temp2"));
tempList.add(jsonObj.getString("temp3"));
tempList.add(jsonObj.getString("temp4"));
tempList.add(jsonObj.getString("temp5"));
tempList.add(jsonObj.getString("temp6"));
MyApp.tempList.clear();
MyApp.tempList = tempList;
List<String> weatherList = new ArrayList<String>();// 未來五天天氣(第一個(gè)是今天)
weatherList.add(jsonObj.getString("weather1"));
weatherList.add(jsonObj.getString("weather2"));
weatherList.add(jsonObj.getString("weather3"));
weatherList.add(jsonObj.getString("weather4"));
weatherList.add(jsonObj.getString("weather5"));
weatherList.add(jsonObj.getString("weather6"));
MyApp.weatherList.clear();
MyApp.weatherList = weatherList;
List<String> tempListMax = new ArrayList<String>(); // 未來五天最高溫度集合(有°符號)
if (temp == 1) {
tempListMax.add(getSaveTemperature(activity));
} else {
tempListMax
.add(getTemperatureMaxAndMin(tempList.get(0))[0 + temp]);
saveTemperature(activity, tempListMax.get(0));
}
tempListMax
.add(getTemperatureMaxAndMin(tempList.get(1 - temp))[0 + temp]);
tempListMax
.add(getTemperatureMaxAndMin(tempList.get(2 - temp))[0 + temp]);
tempListMax
.add(getTemperatureMaxAndMin(tempList.get(3 - temp))[0 + temp]);
weather.setTemperatureMax(tempListMax);
weather.setTodayTemperature(getTemperatureMaxAndMin(tempList.get(0))[0]); // 當(dāng)天溫度(實(shí)時(shí))
weather.setTodayWeather(jsonObj.getString("img_title1")); // 當(dāng)天天氣描述(實(shí)時(shí))
List<String> tempListMin = new ArrayList<String>(); // 未來四天最低溫度集合(有°符號)
tempListMin.add(getTemperatureMaxAndMin(tempList.get(0))[1 - temp]);
tempListMin.add(getTemperatureMaxAndMin(tempList.get(1))[1 - temp]);
tempListMin.add(getTemperatureMaxAndMin(tempList.get(2))[1 - temp]);
tempListMin.add(getTemperatureMaxAndMin(tempList.get(3))[1 - temp]);
weather.setTemperatureMin(tempListMin);
weather.setTomorrowTemperature(tempList.get(1)); // 明天溫度(包括最高溫和最低溫)
if (temp == 1) {
weatherList.add(getSaveWeather(activity));
} else {
weatherList.add(jsonObj.getString("weather" + 1));
saveWeather(activity, weatherList.get(0));
}
weatherList.add(jsonObj.getString("weather" + (2 - temp)));
weatherList.add(jsonObj.getString("weather" + (3 - temp)));
weatherList.add(jsonObj.getString("weather" + (4 - temp)));
weather.setWeather(weatherList);
weather.setTomorrowWeather(weatherList.get(1));
List<String> windList = new ArrayList<String>(); // 未來四天風(fēng)力
windList.add(jsonObj.getString("wind1"));
windList.add(jsonObj.getString("wind2"));
windList.add(jsonObj.getString("wind3"));
windList.add(jsonObj.getString("wind4"));
weather.setWind(windList);
weather.setMaxlist(transplate(tempListMax)); // 未來四天最高溫度集合(無°符號)
weather.setMinlist(transplate(tempListMin)); // 未來四天最低溫度集合(無°符號)
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
// 獲取更新日期 并轉(zhuǎn)換為(X月X日 周X)
private String getDate() {
SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 EEE", Locale.CHINA);
String date = sdf.format(new java.util.Date());
System.out.println(date);
return date;
}
// 獲取更新時(shí)間 并轉(zhuǎn)換為 (小時(shí):分鐘 更新)
private String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.CHINA);
String time = sdf.format(new java.util.Date()) + " " + "更新";
System.out.println(time);
return time;
}
private String getWeek() {
return null;
}
// 獲取最高溫度和最低溫度,有°符號
private String[] getTemperatureMaxAndMin(String str) {
return str.split("~");
}
// 去除最高溫度和最低溫度里的°符號
private List<Integer> transplate(List<String> strList) {
List<Integer> intList = new ArrayList<Integer>();
for (String temp : strList) {
intList.add(Integer.valueOf(temp.split("°")[0]));
}
return intList;
}
// 獲取圖片編號 例如"img" + "1"
private int getJsonPic(JSONObject jsonObj, String str, int index)
throws JSONException {
int result = jsonObj.getInt(str + index);
if (result == 99 && index > 1) {
index--;
result = jsonObj.getInt(str + index);
}
return result;
}
private void saveTemperature(Activity activity, String value) {
// MySharedPreferences mp = new MySharedPreferences(activity);
// mp.writeMessage("temperature", value);
}
// 保存的溫度
private String getSaveTemperature(Activity activity) {
return MySharedPreferences.readMessage(activity,"temperature", "100");
}
private void saveWeather(Activity activity, String value) {
// MySharedPreferences mp = new MySharedPreferences(activity);
// mp.writeMessage("weather", value);
}
// 保存的天氣
private String getSaveWeather(Activity activity) {
return MySharedPreferences.readMessage(activity,"weather", "");
}
private void savePic(Activity activity, int value) {
// MySharedPreferences mp = new MySharedPreferences(activity);
// mp.writeMessage("pic", value);
}
// 保存的天氣圖片編號
private int getSavePic(Activity activity) {
return MySharedPreferences.readMessage(activity,"pic", 99);
}
}
希望本文實(shí)例對大家Android天氣預(yù)報(bào)程序的開發(fā)能夠起到一定的幫助作用。
- 如何通過Android Stduio來編寫一個(gè)完整的天氣預(yù)報(bào)APP
- Android Internet應(yīng)用實(shí)現(xiàn)獲取天氣預(yù)報(bào)的示例代碼
- Android編程實(shí)現(xiàn)類似天氣預(yù)報(bào)圖文字幕垂直滾動(dòng)效果的方法
- android JSON解析數(shù)據(jù) android解析天氣預(yù)報(bào)
- Android天氣預(yù)報(bào)app改進(jìn)版
- Android編程實(shí)現(xiàn)獲取新浪天氣預(yù)報(bào)數(shù)據(jù)的方法
- android調(diào)用國家氣象局天氣預(yù)報(bào)接口json數(shù)據(jù)格式解釋
- Android簡單實(shí)現(xiàn)天氣預(yù)報(bào)App
相關(guān)文章
Android中ListView設(shè)置靜態(tài)數(shù)據(jù)的方法
這篇文章主要介紹了Android中ListView設(shè)置靜態(tài)數(shù)據(jù)的方法,如何為ListView設(shè)置靜態(tài)數(shù)據(jù),感興趣的小伙伴們可以參考一下2015-12-12
Android調(diào)試華為和魅族手機(jī)logcat不顯示的問題
今天小編就為大家分享一篇關(guān)于Android調(diào)試華為和魅族手機(jī)logcat不顯示的問題,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-10-10
Android實(shí)現(xiàn)頁面跳轉(zhuǎn)的全過程記錄
對于android軟件開發(fā)初級學(xué)習(xí)者來說,簡單的頁面跳轉(zhuǎn)是必學(xué)的,這篇文章主要給大家介紹了關(guān)于Android實(shí)現(xiàn)頁面跳轉(zhuǎn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-10-10
Android中ViewPager的PagerTabStrip與PagerTitleStrip用法實(shí)例
這篇文章主要介紹了Android中ViewPager的PagerTabStrip與PagerTitleStrip用法實(shí)例,這兩個(gè)子控件一般被用作添加標(biāo)題,在實(shí)際效果上并不是那么好控制,使用的時(shí)候需要謹(jǐn)慎,需要的朋友可以參考下2016-06-06
Android開發(fā)微信APP支付功能的要點(diǎn)小結(jié)
微信支付現(xiàn)在在日常生活中隨處可見,而關(guān)于Android開發(fā)微信支付的文章網(wǎng)上也很多,所以這篇文章主要介紹的是在Android開發(fā)微信APP支付功能的要注意的要點(diǎn),有需要的可以參考借鑒。2016-08-08
Android GridView 滑動(dòng)條設(shè)置一直顯示狀態(tài)(推薦)
這篇文章主要介紹了Android GridView 滑動(dòng)條設(shè)置一直顯示狀態(tài)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-12-12
Android中AlertDialog的六種創(chuàng)建方式
這篇文章主要介紹了Android中AlertDialog的六種創(chuàng)建方式的相關(guān)資料,需要的朋友可以參考下2016-07-07

