您的位置:首页 > 编程语言

第一行代码酷欧天气开发(三)

2016-09-10 20:41 489 查看
这步是最关键的一步,编写用于遍历省市县数据的activity了,在activity包下面新建ChooseAreaActivity继承自Activity

该类的逻辑是下面这样的:

在onCreate()方法中显示获取到了一些控件的实例,然后去初始化ArrayAdapter,将他设置为listview的适配器,之后去获取CoolWeatherDB的实例,并给ListView设置点击事件,到这里我们的初始化工作就算是完成了。

在onCreate()方法的最后,调用了queryprovinces()方法,也就是从这里开始加载省级数据的,queryProvinces()方法的内部首先会调用CoolWeatherDB的loadProvinces()方法来从数据库中读取省级数据,如果读取到了就直接将数据显示到界面上,如果没有读取到就调用queryFromServer()方法从服务器上查询数据。

queryFromServer()方法会先根据闯入的参数来拼装查询地址,这个地址就是我们在最前面分析过的,确定了查询地址后,接下来就调用HttpUtil的sendHttpResquest()方法来向服务器发送请求,响应的数据会调onFinish()方法,然后我们在这里去调用Utility的handleProvinceResponse()方法来解析和处理服务器返回的数据,并存储到到数据库中,接下来的一步很关键,在解析和处理完数据之后,我们再次调用了queryProvinces()方法来重新加载省级数据,由于queryProvinces()方法牵扯到了UI操作,因此必须要在这线程中调用,这里接住了runOnUiThread()方法来实现从子线程切换到主线程,他的实现原理也是基于异步任务处理机制的,现在数据库中已经有了数据,因此调用queryProvinces()会直接将数据显示到界面上了

当你点击某个省的时候会进入listview的onItenClick()方法,这个时候会根据当前的级别来判断逝去调用queryCities()方法还是queryCounties()方法,这两个方法的流程和queryProvinces()方法基本相同,

package com.coolweather.app.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.ActionBar.Tab;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.coolweather.app.R;
import com.coolweather.app.db.CoolWeatherDB;
import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;

/**
* @author aiyuan
*
*/
public class ChooseAreaActivity extends Activity {
String TAG = "ChooseAreaActivity";

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;
/**
* 是否从WeatherActivity中跳转过来。
*/
private boolean isFromWeatherActivity;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false);
Log.d(TAG, "isFromWeatherActivity=" + isFromWeatherActivity);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ChooseAreaActivity.this);
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() {
@Override
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();
} else if (currentLevel == LEVEL_COUNTY) {
String countyCode = countyList.get(index).getCountyCode();
Log.d(TAG, countyCode+"h");
Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class);
intent.putExtra("county_code", countyCode);
startActivity(intent);
finish();
}
}
});
queryProvinces();  // 加载省级数据
}

/**
* 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询。
*/
private void queryProvinces() {
provinceList = coolWeatherDB.loadProvince();
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : prov
d82d
inceList) {
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() {
Log.d(TAG, selectedCity.getId()+"");
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");
}
}

/**
* 根据传入的代号和类型从服务器上查询省市县数据。
* @param code
* @param type
*/
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() {
@Override
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() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
} else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}

@Override
public void onError(Exception e) {
// 通过runOnUiThread()方法回到主线程处理逻辑
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this,
"加载失败", Toast.LENGTH_SHORT).show();
}
});
}
});
}

/**
* 显示进度对话框
*/
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按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出。
*/
@Override
public void onBackPressed() {
if (currentLevel == LEVEL_COUNTY) {
queryCities();
} else if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else {
if (isFromWeatherActivity) {
Log.d(TAG, "issi");
Intent intent = new Intent(this, WeatherActivity.class);
startActivity(intent);
}
finish();
}
}

}


这里,我们还需要在xml文件中注册这个活动和给他网络权限,如下

<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>


然后给网络权限

<uses-permission android:name="android.permission.INTERNET"/>


下面几张截图是对流程的简单说明和方法的阐述

listview的点击事件



查询全国所有的省份信息



接下里是HttpUtil.sendHttpRequest()方法





ok,这一步也完成了。

下一步就要显示天气信息了

第一行代码酷欧天气开发(四)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android+