进入实战,开发酷欧天气(三)
来源:互联网 发布:oa软件下载 编辑:程序博客网 时间:2024/06/08 14:38
目标的坚定是性格中最必要的力量源泉之一,也是成功的利器之一。
本讲内容:遍历全国省市县数据
1、全国所有省市县的数据都是从服务器端获取到的,因此这里和服务器的交互不可少的,所以在util包下增加一个HttpUtil类,代码如下:
public class HttpUtil {public static void sendHttpRequest(final String address,final HttpCallbackListener listener) {new Thread(new Runnable() {public void run() {HttpURLConnection connection = null;try {URL url = new URL(address);connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(8000);connection.setReadTimeout(8000);InputStream in = connection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}if (listener != null) {// 回调onFinish()方法listener.onFinish(response.toString());}} catch (Exception e) {if (listener != null) {// 回调onError()方法listener.onError(e);}} finally {if (connection != null) {connection.disconnect();}}}}).start();}}HttpUtil类中使用到了HttpCallbackListener接口来回调服务器返回的结果,因此我们还需要添加这个接口,如下:
public interface HttpCallbackListener {void onFinish(String response);void onError(Exception e);}
由于服务器返回的省市县数据都是“代号|城市,代号|城市”这种格式,所以我们最好再提供一个工具类来解析和处理这种数据。在util包下新建一个Utility类,代码如下:
public class Utility {/** * 解析和处理服务器返回的省级数据 */public synchronized static boolean handleProvincesResponse(CoolWeatherDB coolWeatherDB, String response) {if (!TextUtils.isEmpty(response)) {String[] allProvinces = response.split(",");if (allProvinces != null && allProvinces.length > 0) {for (String p : allProvinces) {String[] array = p.split("\\|");Province province = new Province();province.setProvinceCode(array[0]);province.setProvinceName(array[1]);// 将解析出来的数据存储到Province表coolWeatherDB.saveProvince(province);}return true;}}return false;}/** * 解析和处理服务器返回的市级数据 */public static boolean handleCitiesResponse(CoolWeatherDB coolWeatherDB,String response, int provinceId) {if (!TextUtils.isEmpty(response)) {String[] allCities = response.split(",");if (allCities != null && allCities.length > 0) {for (String c : allCities) {String[] array = c.split("\\|");City city = new City();city.setCityCode(array[0]);city.setCityName(array[1]);city.setProvinceId(provinceId);// 将解析出来的数据存储到City表coolWeatherDB.saveCity(city);}return true;}}return false;}/** * 解析和处理服务器返回的县级数据 */public static boolean handleCountiesResponse(CoolWeatherDB coolWeatherDB,String response, int cityId) {if (!TextUtils.isEmpty(response)) {String[] allCounties = response.split(",");if (allCounties != null && allCounties.length > 0) {for (String c : allCounties) {String[] array = c.split("\\|");County county = new County();county.setCountyCode(array[0]);county.setCountyName(array[1]);county.setCityId(cityId);// 将解析出来的数据存储到County表coolWeatherDB.saveCounty(county);}return true;}}return false;}/** * 解析服务器返回的JSON数据,并将解析出的数据存储到本地。 */public static void handleWeatherResponse(Context context, String response) {try {JSONObject jsonObject = new JSONObject(response);JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");String cityName = weatherInfo.getString("city");String weatherCode = weatherInfo.getString("cityid");String temp1 = weatherInfo.getString("temp1");String temp2 = weatherInfo.getString("temp2");String weatherDesp = weatherInfo.getString("weather");String publishTime = weatherInfo.getString("ptime");saveWeatherInfo(context, cityName, weatherCode, temp1, temp2,weatherDesp, publishTime);} catch (JSONException e) {e.printStackTrace();}}/** * 将服务器返回的所有天气信息存储到SharedPreferences文件中。 */public static void saveWeatherInfo(Context context, String cityName,String weatherCode, String temp1, String temp2, String weatherDesp,String publishTime) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA);SharedPreferences.Editor editor = 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(new Date()));editor.commit();}}提供了三个方法分别用于解析和处理服务器返回的省级、市级、县级数据。解析的规则就是先按逗号分隔,再按单竖线分隔,接着将解析出来的数据设置到实体类中,最后调用CoolWeatherDB中的三个save()方法将数据存储到相应的表中。
2、开始写界面
下面是res/layout/choose_area.xml布局文件
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns: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/title_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#fff" android:textSize="24sp" /> </RelativeLayout> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView></LinearLayout>
下面是BaseActivity.java文件
/** * 设置activity的基础类 * 变量可以在这里设置 (所有活动都可以继承) */ public class BaseActivity extends Activity {public static final String TAG="tag";protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);}/** *用于所有活动测试 */public void toast(String msg){Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); Log.d(TAG, msg);}}
下面是ChooseAreaActivity.java文件
public class ChooseAreaActivity extends BaseActivity {public static final int LEVEL_PROVINCE = 0;public static final int LEVEL_CITY = 1;public static final int LEVEL_COUNTY = 2;private ProgressDialog progressDialog;private TextView titleText;private ListView listView;private ArrayAdapter<String> adapter;private CoolWeatherDB coolWeatherDB;private List<String> dataList = new ArrayList<String>();/** * 省列表 */private List<Province> provinceList;/** * 市列表 */private List<City> cityList;/** * 县列表 */private List<County> countyList;/** * 选中的省份 */private Province selectedProvince;/** * 选中的城市 */private City selectedCity;/** * 当前选中的级别 */private int currentLevel;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);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 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);listView.setAdapter(adapter);coolWeatherDB = CoolWeatherDB.getInstance(this);listView.setOnItemClickListener(new OnItemClickListener() {public void onItemClick(AdapterView<?> arg0, View view, int index,long arg3) {if (currentLevel == LEVEL_PROVINCE) {selectedProvince = provinceList.get(index);queryCities();} else if (currentLevel == LEVEL_CITY) {selectedCity = cityList.get(index);queryCounties();} }});queryProvinces(); // 加载省级数据}/** * 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询。 */private void queryProvinces() {provinceList = coolWeatherDB.loadProvinces();if (provinceList.size() > 0) {dataList.clear();for (Province province : provinceList) {dataList.add(province.getProvinceName());}adapter.notifyDataSetChanged();listView.setSelection(0);titleText.setText("中国");currentLevel = LEVEL_PROVINCE;} else {queryFromServer(null, "province");}}/** * 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询。 */private void queryCities() {cityList = coolWeatherDB.loadCities(selectedProvince.getId());if (cityList.size() > 0) {dataList.clear();for (City city : cityList) {dataList.add(city.getCityName());}adapter.notifyDataSetChanged();listView.setSelection(0);titleText.setText(selectedProvince.getProvinceName());currentLevel = LEVEL_CITY;} else {queryFromServer(selectedProvince.getProvinceCode(), "city");}}/** * 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询。 */private void queryCounties() {countyList = coolWeatherDB.loadCounties(selectedCity.getId());if (countyList.size() > 0) {dataList.clear();for (County county : countyList) {dataList.add(county.getCountyName());}adapter.notifyDataSetChanged();listView.setSelection(0);titleText.setText(selectedCity.getCityName());currentLevel = LEVEL_COUNTY;} else {queryFromServer(selectedCity.getCityCode(), "county");}}/** * 根据传入的代号和类型从服务器上查询省市县数据。 */private void queryFromServer(final String code, final String type) {String address;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, new HttpCallbackListener() {public void onFinish(String response) {boolean result = false;if ("province".equals(type)) {result = Utility.handleProvincesResponse(coolWeatherDB,response);} else if ("city".equals(type)) {result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId());} else if ("county".equals(type)) {result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId());}if (result) {// 通过runOnUiThread()方法回到主线程处理逻辑runOnUiThread(new Runnable() {public void run() {closeProgressDialog();if ("province".equals(type)) {queryProvinces();} else if ("city".equals(type)) {queryCities();} else if ("county".equals(type)) {queryCounties();}}});}}public void onError(Exception e) {// 通过runOnUiThread()方法回到主线程处理逻辑runOnUiThread(new Runnable() {public void run() {closeProgressDialog();toast("加载失败");}});}});}/** * 显示进度对话框 */private void showProgressDialog() {if (progressDialog == null) {progressDialog = new ProgressDialog(this);progressDialog.setMessage("正在加载...");progressDialog.setCanceledOnTouchOutside(false);}progressDialog.show();}/** * 关闭进度对话框 */private void closeProgressDialog() {if (progressDialog != null) {progressDialog.dismiss();}}/** * 捕获Back按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出。 */public void onBackPressed() {if (currentLevel == LEVEL_COUNTY) {queryCities();} else if (currentLevel == LEVEL_CITY) {queryProvinces();} else {finish();}}}
AndroidManifest.xml中的代码:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.coolweather.app" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="activity.ChooseAreaActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
git add .
git commit -m "完成遍历省市县三级列表的功能。"
git push origin master
2 0
- 进入实战,开发酷欧天气(三)
- 进入实战,开发酷欧天气(一)
- 进入实战,开发酷欧天气(二)
- 进入实战,开发酷欧天气(四)
- 进入实战,开发酷欧天气(五)
- 阅读郭林《第一行代码》的笔记——第14章 进入实战,开发酷欧天气
- 酷欧天气实战
- 第一行代码酷欧天气开发(三)
- 天气开发1——第二行代码(酷欧天气)
- 天气开发2——第二行代码(酷欧天气)
- 天气开发3——第二行代码(酷欧天气)
- 天气开发4——第二行代码(酷欧天气)
- 酷欧天气开发笔记3:显示天气信息
- 第一行代码酷欧天气开发(一)
- 第一行代码酷欧天气开发(二)
- 第一行代码酷欧天气开发(四)
- 第一行代码酷欧天气开发(五)
- Android实战:CoolWeather酷欧天气(加强版数据接口)代码详解(上)
- C++编程思想学习笔记---第12章 运算符重载
- 初学python
- ADS2009U1安装破解步骤及文件下载地址(亲测XP_WIN7成功)
- iOS图片的多选择,删除,和本地显示
- zend studio自动添加文件注释和方法注释
- 进入实战,开发酷欧天气(三)
- Service的生命周期与Activity生命周期区别
- 反射入门(转)
- 白话经典算法系列之二 直接插入排序的三种实现
- ts 中 pts 计算
- 理解操作系统的sleep函数
- 猪猪侠那里弄的python递归脚本
- SpringMVC、MyBatis声明式事务管理
- 简单身份证合法性验证JAVA