zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Android天气预报之基于HttpGet对象解析天气数据的方法

Android方法对象数据 解析 基于 天气 天气预报
2023-06-13 09:15:41 时间

本文实例所述为Android天气预报之解析天气数据的代码,可实现获取HttpGet对象读取天气网站天气数据,并从数据中解析出天气数据,比如温度、温度、风力、风向、未来几天天气趋势、当天天气状况、空气污染指数等信息,还包括了调用对应的图片或天气动画文件,对于开发android天气预报程序的可以参考本文实例。

具体功能代码如下:

importjava.io.IOException;
importjava.text.SimpleDateFormat;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Locale;
importnet.tsz.afinal.FinalHttp;
importnet.tsz.afinal.http.AjaxCallBack;
importorg.apache.http.HttpResponse;
importorg.apache.http.HttpStatus;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.util.EntityUtils;
importorg.json.JSONException;
importorg.json.JSONObject;
importorg.lmw.weather.MyApp;
importorg.lmw.weather.entity.WeatherEntity;
importandroid.app.Activity;
importandroid.os.Handler;
importandroid.os.Message;
/**
*解析天气数据
*@authorDave
*/
publicclassWeatherData{
privateActivityactivity;
privateFinalHttpfh;
publicstaticStringdef_weather_key="def_weather";
publicWeatherData(Activityactivity){
this.activity=activity;
fh=newFinalHttp();
fh.configTimeout(1000*3);
}
publicvoidgetData(finalStringcityId,finalHandlerhd){
StringBuffersb_url=newStringBuffer();
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");
finalMessagemsg=newMessage();
fh.get(sb_url.toString(),newAjaxCallBack(){
@Override
publicvoidonSuccess(Objectt){
super.onSuccess(t);
MySharedPreferences.writeMessage(activity,"def_weather",t.toString());
msg.what=0;
msg.obj=parseJson(t.toString());
hd.sendMessage(msg);
}
@Override
publicvoidonFailure(Throwablet,interrorNo,StringstrMsg){
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);
}
});
}
privateStringconnServerForResult(StringstrUrl){
//获取HttpGet对象
HttpGethttpRequest=newHttpGet(strUrl);
StringstrResult="";
try{
//HttpClient对象
HttpClienthttpClient=newDefaultHttpClient();
//获得HttpResponse对象
HttpResponsehttpResponse=httpClient.execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//取得返回的数据
strResult=EntityUtils.toString(httpResponse.getEntity());
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
System.out.println("rresult"+strResult);
returnstrResult;//返回结果
}
//数据解析
privateWeatherEntityparseJson(StringstrResult){
WeatherEntityweather=null;
try{
JSONObjectjsonObj=newJSONObject(strResult.replace("℃","°"))
.getJSONObject("weatherinfo");
weather=newWeatherEntity();
intftime=jsonObj.getInt("fchh");//更新时间(整点)【更新时间确定temp属于哪天】
inttemp=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());//更新时间
weather.setRefreshWeek(getWeek());//更新星期
weather.setPicIndex(jsonObj.getInt("img1"));//当天天气图片编号
List<Integer>topPic=newArrayList<Integer>();//最高温时的图片编号
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=newArrayList<Integer>();//最低温时的图片编号
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=newArrayList<String>();//未来五天温度(第一个是今天)
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=newArrayList<String>();//未来五天天气(第一个是今天)
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=newArrayList<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]);//当天温度(实时)
weather.setTodayWeather(jsonObj.getString("img_title1"));//当天天气描述(实时)
List<String>tempListMin=newArrayList<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=newArrayList<String>();//未来四天风力
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(JSONExceptione){
e.printStackTrace();
}
returnweather;
}
//获取更新日期并转换为(X月X日周X)
privateStringgetDate(){
SimpleDateFormatsdf=newSimpleDateFormat("MM月dd日EEE",Locale.CHINA);
Stringdate=sdf.format(newjava.util.Date());
System.out.println(date);
returndate;
}
//获取更新时间并转换为(小时:分钟更新)
privateStringgetTime(){
SimpleDateFormatsdf=newSimpleDateFormat("HH:mm",Locale.CHINA);
Stringtime=sdf.format(newjava.util.Date())+""+"更新";
System.out.println(time);
returntime;
}
privateStringgetWeek(){
returnnull;
}
//获取最高温度和最低温度,有°符号
privateString[]getTemperatureMaxAndMin(Stringstr){
returnstr.split("~");
}
//去除最高温度和最低温度里的°符号
privateList<Integer>transplate(List<String>strList){
List<Integer>intList=newArrayList<Integer>();
for(Stringtemp:strList){
intList.add(Integer.valueOf(temp.split("°")[0]));
}
returnintList;
}
//获取图片编号例如"img"+"1"
privateintgetJsonPic(JSONObjectjsonObj,Stringstr,intindex)
throwsJSONException{
intresult=jsonObj.getInt(str+index);
if(result==99&&index>1){
index--;
result=jsonObj.getInt(str+index);
}
returnresult;
}
privatevoidsaveTemperature(Activityactivity,Stringvalue){
//MySharedPreferencesmp=newMySharedPreferences(activity);
//mp.writeMessage("temperature",value);
}
//保存的温度
privateStringgetSaveTemperature(Activityactivity){
returnMySharedPreferences.readMessage(activity,"temperature","100");
}
privatevoidsaveWeather(Activityactivity,Stringvalue){
//MySharedPreferencesmp=newMySharedPreferences(activity);
//mp.writeMessage("weather",value);
}
//保存的天气
privateStringgetSaveWeather(Activityactivity){
returnMySharedPreferences.readMessage(activity,"weather","");
}
privatevoidsavePic(Activityactivity,intvalue){
//MySharedPreferencesmp=newMySharedPreferences(activity);
//mp.writeMessage("pic",value);
}
//保存的天气图片编号
privateintgetSavePic(Activityactivity){
returnMySharedPreferences.readMessage(activity,"pic",99);
}
}

希望本文实例对大家Android天气预报程序的开发能够起到一定的帮助作用。