Android 遍历全国的地区二(获取天气)
2015-09-16 09:48
423 查看
根据上次的内容
1.界面布局
weather_layout.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp" android:background="#484E61"> <TextView android:id="@+id/city_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#fff" android:textSize="24sp"/> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#27A5F9"> <TextView android:id="@+id/publish_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:textColor="#FFF" android:textSize="18sp"/> <LinearLayout android:id="@+id/weather_info_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="vertical"> <TextView android:id="@+id/current_date" android:layout_width="wrap_content" android:layout_height="40dp" android:gravity="center" android:textColor="#FFF" android:textSize="18sp"/> <TextView android:id="@+id/weather_desp" android:layout_width="wrap_content" android:layout_height="60dp" android:layout_gravity="center_horizontal" android:gravity="center" android:textColor="#FFF" android:textSize="40sp"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="60dp" android:layout_gravity="center_horizontal" android:orientation="horizontal"> <TextView android:id="@+id/temp1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:textColor="#FFF" android:textSize="40sp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:text="~" android:textColor="#FFF" android:textSize="40sp"/> <TextView android:id="@+id/temp2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:textColor="#FFF" android:textSize="40sp"/> </LinearLayout> </LinearLayout> </RelativeLayout> </LinearLayout>
2.解析服务器返回的数据,存储到本地
Utility.java
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.Locale;
importorg.json.JSONException;
importorg.json.JSONObject;
importandroid.content.Context;
importandroid.content.SharedPreferences;
importandroid.preference.PreferenceManager;
importandroid.text.TextUtils;
publicclassUtility{
/**
*解析和处理服务器返回的省级数据
*/
publicsynchronizedstaticbooleanhandleProvincesResponse(
CoolWeatherDBcoolWeatherDB,Stringresponse){
if(!TextUtils.isEmpty(response)){
String[]allProvinces=response.split(",");
if(allProvinces!=null&&allProvinces.length>0){
for(Stringp:allProvinces){
String[]array=p.split("\\|");
Provinceprovince=newProvince();
province.setProvinceCode(array[0]);
province.setProvinceName(array[1]);
//将解析出来的数据存储到Province表
coolWeatherDB.saveProvince(province);
}
returntrue;
}
}
returnfalse;
}
/**
*解析和处理服务器返回的市级数据
*/
publicstaticbooleanhandleCitiesResponse(CoolWeatherDBcoolWeatherDB,
Stringresponse,intprovinceId){
if(!TextUtils.isEmpty(response)){
String[]allCities=response.split(",");
if(allCities!=null&&allCities.length>0){
for(Stringc:allCities){
String[]array=c.split("\\|");
Citycity=newCity();
city.setCityCode(array[0]);
city.setCityName(array[1]);
city.setProvinceId(provinceId);
//将解析出来的数据存储到City表
coolWeatherDB.saveCity(city);
}
returntrue;
}
}
returnfalse;
}
/**
*解析和处理服务器返回的县级数据
*/
publicstaticbooleanhandleCountiesResponse(CoolWeatherDBcoolWeatherDB,
Stringresponse,intcityId){
if(!TextUtils.isEmpty(response)){
String[]allCounties=response.split(",");
if(allCounties!=null&&allCounties.length>0){
for(Stringc:allCounties){
String[]array=c.split("\\|");
Countycounty=newCounty();
county.setCountyCode(array[0]);
county.setCountyName(array[1]);
county.setCityId(cityId);
//将解析出来的数据存储到County表
coolWeatherDB.saveCounty(county);
}
returntrue;
}
}
returnfalse;
}
publicstaticvoidhandleWeatherResponse(Contextcontext,Stringresponse){
try{
JSONObjectjsonObject=newJSONObject(response);
JSONObjectweatherInfo=jsonObject.getJSONObject("weatherinfo");
StringcityName=weatherInfo.getString("city");
StringweatherCode=weatherInfo.getString("cityid");
Stringtemp1=weatherInfo.getString("temp1");
Stringtemp2=weatherInfo.getString("temp2");
StringweatherDesp=weatherInfo.getString("weather");
StringpublishTime=weatherInfo.getString("ptime");
saveWeatherInfo(context,cityName,weatherCode,temp1,temp2,
weatherDesp,publishTime);
}catch(JSONExceptione){
e.printStackTrace();
}
}
/**
*将服务器返回的所有天气信息存储到SharedPreferences文件中。
*/
publicstaticvoidsaveWeatherInfo(Contextcontext,StringcityName,
StringweatherCode,Stringtemp1,Stringtemp2,StringweatherDesp,String
publishTime){
SimpleDateFormatsdf=newSimpleDateFormat("yyyy年M月d日",
Locale.CHINA);
SharedPreferences.Editoreditor=PreferenceManager
.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected",true);
editor.putString("city_name",cityName);
editor.putString("weather_code",weatherCode);
editor.putString("temp1",temp1);
editor.putString("temp2",temp2);
editor.putString("weather_desp",weatherDesp);
editor.putString("publish_time",publishTime);
editor.putString("current_date",sdf.format(newDate()));
editor.commit();
}
}
3.创建一个活动界面
importandroid.app.Activity;
importandroid.content.SharedPreferences;
importandroid.os.Bundle;
importandroid.preference.PreferenceManager;
importandroid.text.TextUtils;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.view.Window;
importandroid.widget.Button;
importandroid.widget.LinearLayout;
importandroid.widget.TextView;
publicclassWeatherActivityextendsActivityimplementsOnClickListener{
privateLinearLayoutweatherInfoLayout;
/**
*用于显示城市名第14章进入实战,开发酷欧天气533
*/
privateTextViewcityNameText;
/**
*用于显示发布时间
*/
privateTextViewpublishText;
/**
*用于显示天气描述信息
*/
privateTextViewweatherDespText;
/**
*用于显示气温1
*/
privateTextViewtemp1Text;
/**
*用于显示气温2
*/
privateTextViewtemp2Text;
/**
*用于显示当前日期
*/
privateTextViewcurrentDateText;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.weather_layout);
//初始化各控件
weatherInfoLayout=(LinearLayout)findViewById(R.id.weather_info_layout);
cityNameText=(TextView)findViewById(R.id.city_name);
publishText=(TextView)findViewById(R.id.publish_text);
weatherDespText=(TextView)findViewById(R.id.weather_desp);
temp1Text=(TextView)findViewById(R.id.temp1);
temp2Text=(TextView)findViewById(R.id.temp2);
currentDateText=(TextView)findViewById(R.id.current_date);
/*
*switchCity=(Button)findViewById(R.id.switch_city);refreshWeather
*=(Button)findViewById(R.id.refresh_weather);
*/
StringcountyCode=getIntent().getStringExtra("county_code");
if(!TextUtils.isEmpty(countyCode)){
//有县级代号时就去查询天气
publishText.setText("同步中...");
weatherInfoLayout.setVisibility(View.INVISIBLE);
cityNameText.setVisibility(View.INVISIBLE);
queryWeatherCode(countyCode);
}else{
//没有县级代号时就直接显示本地天气
showWeather();
}
/*switchCity.setOnClickListener(this);
refreshWeather.setOnClickListener(this);*/
}
@Override
publicvoidonClick(Viewv){
}
/**
*查询县级代号所对应的天气代号。
*/
privatevoidqueryWeatherCode(StringcountyCode){
Stringaddress="http://www.weather.com.cn/data/list3/city"
+countyCode+".xml";
queryFromServer(address,"countyCode");
}
/**
*查询天气代号所对应的天气。
*/
privatevoidqueryWeatherInfo(StringweatherCode){
Stringaddress="http://www.weather.com.cn/data/cityinfo/"
+weatherCode+".html";
queryFromServer(address,"weatherCode");
}
/**
*根据传入的地址和类型去向服务器查询天气代号或者天气信息。
*/
privatevoidqueryFromServer(finalStringaddress,finalStringtype){
HttpUtil.sendHttpRequest(address,newHttpCallbackListener(){
@Override
publicvoidonFinish(finalStringresponse){
if("countyCode".equals(type)){
if(!TextUtils.isEmpty(response)){
//从服务器返回的数据中解析出天气代号
String[]array=response.split("\\|");
if(array!=null&&array.length==2){
StringweatherCode=array[1];
queryWeatherInfo(weatherCode);
}
}
}elseif("weatherCode".equals(type)){
//处理服务器返回的天气信息
Utility.handleWeatherResponse(WeatherActivity.this,
response);
runOnUiThread(newRunnable(){
@Override
publicvoidrun(){
showWeather();
}
});
}
}
@Override
publicvoidonError(Exceptione){
runOnUiThread(newRunnable(){
@Override
publicvoidrun(){
publishText.setText("同步失败");
}
});
}
});
}
/**
*从SharedPreferences文件中读取存储的天气信息,并显示到界面上。
*/
privatevoidshowWeather(){
SharedPreferencesprefs=PreferenceManager
.getDefaultSharedPreferences(this);
cityNameText.setText(prefs.getString("city_name",""));
temp1Text.setText(prefs.getString("temp1",""));
temp2Text.setText(prefs.getString("temp2",""));
weatherDespText.setText(prefs.getString("weather_desp",""));
publishText.setText("今天"+prefs.getString("publish_time","")+"发布");
currentDateText.setText(prefs.getString("current_date",""));
weatherInfoLayout.setVisibility(View.VISIBLE);
cityNameText.setVisibility(View.VISIBLE);
}
}
4.主界面跳转到天气界面
ChooseAreaActivity.java
importjava.util.ArrayList;
importjava.util.List;
importandroid.app.Activity;
importandroid.app.ProgressDialog;
importandroid.content.Intent;
importandroid.content.SharedPreferences;
importandroid.os.Bundle;
importandroid.preference.PreferenceManager;
importandroid.text.TextUtils;
importandroid.view.View;
importandroid.view.Window;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.OnItemClickListener;
importandroid.widget.ArrayAdapter;
importandroid.widget.ListView;
importandroid.widget.TextView;
importandroid.widget.Toast;
importcom.coolweather.app.R;
importcom.coolweather.app.db.CoolWeatherDB;
importcom.coolweather.app.model.City;
importcom.coolweather.app.model.County;
importcom.coolweather.app.model.Province;
importcom.coolweather.app.util.HttpCallbackListener;
importcom.coolweather.app.util.HttpUtil;
importcom.coolweather.app.util.Utility;
publicclassChooseAreaActivityextendsActivity{
publicstaticfinalintLEVEL_PROVINCE=0;
publicstaticfinalintLEVEL_CITY=1;
publicstaticfinalintLEVEL_COUNTY=2;
privateProgressDialogprogressDialog;
privateTextViewtitleText;
privateListViewlistView;
privateArrayAdapter<String>adapter;
privateCoolWeatherDBcoolWeatherDB;
privateList<String>dataList=newArrayList<String>();
/**
*省列表
*/
privateList<Province>provinceList;
/**
*市列表
*/
privateList<City>cityList;
/**
*县列表
*/
privateList<County>countyList;
/**
*选中的省份
*/
privateProvinceselectedProvince;
privateCityselectedCity;
privateintcurrentLevel;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
SharedPreferencesprefs=PreferenceManager
.getDefaultSharedPreferences(this);
if(prefs.getBoolean("city_selected",false)){
Intentintent=newIntent(this,WeatherActivity.class);
startActivity(intent);
finish();
return;
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.choose_area);
listView=(ListView)findViewById(R.id.list_view);
titleText=(TextView)findViewById(R.id.title_text);
adapter=newArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
coolWeatherDB=CoolWeatherDB.getInstance(this);
listView.setOnItemClickListener(newOnItemClickListener(){
@Override
publicvoidonItemClick(AdapterView<?>arg0,Viewview,intindex,
longarg3){
if(currentLevel==LEVEL_PROVINCE){
selectedProvince=provinceList.get(index);
queryCities();
}elseif(currentLevel==LEVEL_CITY){
selectedCity=cityList.get(index);
queryCounties();
}elseif(currentLevel==LEVEL_COUNTY){
StringcountyCode=countyList.get(index).getCountyCode();
Intentintent=newIntent(ChooseAreaActivity.this,
WeatherActivity.class);
intent.putExtra("county_code",countyCode);
startActivity(intent);
finish();
}
}
});
queryProvinces();//加载省级数据
}
/**
*查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询。
*/
privatevoidqueryProvinces(){
provinceList=coolWeatherDB.loadProvinces();
if(provinceList.size()>0){
dataList.clear();
for(Provinceprovince:provinceList){
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("中国");
currentLevel=LEVEL_PROVINCE;
}else{
queryFromServer(null,"province");
}
}
/**
*查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询。
*/
privatevoidqueryCities(){
cityList=coolWeatherDB.loadCities(selectedProvince.getId());
if(cityList.size()>0){
dataList.clear();
for(Citycity:cityList){
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedProvince.getProvinceName());
currentLevel=LEVEL_CITY;
}else{
queryFromServer(selectedProvince.getProvinceCode(),"city");
}
}
/**
*查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询。
*/
privatevoidqueryCounties(){
countyList=coolWeatherDB.loadCounties(selectedCity.getId());
if(countyList.size()>0){
dataList.clear();
for(Countycounty:countyList){
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedCity.getCityName());
currentLevel=LEVEL_COUNTY;
}else{
queryFromServer(selectedCity.getCityCode(),"county");
}
}
/**
*根据传入的代号和类型从服务器上查询省市县数据。*/
privatevoidqueryFromServer(finalStringcode,finalStringtype){
Stringaddress;
if(!TextUtils.isEmpty(code)){
address="http://www.weather.com.cn/data/list3/city"+code
+".xml";
}else{
address="http://www.weather.com.cn/data/list3/city.xml";
}
showProgressDialog();
HttpUtil.sendHttpRequest(address,newHttpCallbackListener(){
@Override
publicvoidonFinish(Stringresponse){
booleanresult=false;
if("province".equals(type)){
result=Utility.handleProvincesResponse(coolWeatherDB,
response);
}elseif("city".equals(type)){
result=Utility.handleCitiesResponse(coolWeatherDB,
response,selectedProvince.getId());
}elseif("county".equals(type)){
result=Utility.handleCountiesResponse(coolWeatherDB,
response,selectedCity.getId());
}
if(result){
//通过runOnUiThread()方法回到主线程处理逻辑
runOnUiThread(newRunnable(){
@Override
publicvoidrun(){
closeProgressDialog();
if("province".equals(type)){
queryProvinces();
}elseif("city".equals(type)){
queryCities();
}elseif("county".equals(type)){
queryCounties();
}
}
});
}
}
@Override
publicvoidonError(Exceptione){
//通过runOnUiThread()方法回到主线程处理逻辑
runOnUiThread(newRunnable(){
@Override
publicvoidrun(){
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this,"加载失败",
Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
*显示进度对话框
*/
privatevoidshowProgressDialog(){
if(progressDialog==null){
progressDialog=newProgressDialog(this);
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
*关闭进度对话框
*/
privatevoidcloseProgressDialog(){
if(progressDialog!=null){
progressDialog.dismiss();
}
}
/**
*捕获Back按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出。*/
@Override
publicvoidonBackPressed(){
if(currentLevel==LEVEL_COUNTY){
queryCities();
}elseif(currentLevel==LEVEL_CITY){
queryProvinces();
}else{
finish();
}
}
}
5.记得注册新的活动
相关文章推荐
- vlc android 移植版编译
- Android NDK具体作用讲解
- Android仿qq登陆界面
- android 制作9.png图片
- Android快速开发工具ButterKnife Zelezny注解框架使用教程
- Android --SwipeRefreshLayout 下拉刷新
- Android-ViewPager( 切换动画实现 , 兼容性实现)
- android - Toast 了解及使用
- 关于Android4.4以上版本的外置存储器路径问题
- android 制作.9.png图片
- Android debug cmd
- android ListView 几个重要属性
- Android--调用系统照相机拍照与摄像
- Android的ListView数据更新后,如何使最新的条目可以自动滚动到可视范围内?
- 【Android】socket局域网通信
- Android 多媒体应用:调用摄像头拍照
- android设置时间日期
- Android开发学习笔记:Intent的简介以及属性的详解
- android批量文件上传(服务器采用servlet处理)
- Android中.9图片的了解和制作过程