アンドロイド天気応用の練習
33465 ワード
, 。
Demo。
。
Android ,![ ](https://img-blog.csdn.net/20160104115329059)
。 SQLite 、 、 , 。 。
。
public class ChooseAreaActivity extends AppCompatActivity {
// 。
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 adapter;
private ZIqiweatherDB zIqiweatherDB;
private List dataList = new ArrayList();
/**
*
* @param savedInstanceState
*/
private List provinceList;
/**
*
* @param savedInstanceState
*/
private List cityList;
/**
*
* @param savedInstanceState
*/
private List countyList;
/**
*
* @param savedInstanceState
*/
private Province selectedProvince;
/**
*
* @param savedInstanceState
*/
private City selectedCity;
/**
*
* @param savedInstanceState
*/
private int currentLevel;
/**
* weatherareaActivity
* @param savedInstanceState
*/
private boolean isFromWeatherActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity",false);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
if (preferences.getBoolean("city_selected",false)&& !isFromWeatherActivity){
Intent intent = new Intent(this,WeatherActivity.class);
startActivity(intent);
finish();
return;
}
setContentView(R.layout.activity_choose_area);
listView = (ListView) findViewById(R.id.list_view);
titleText = (TextView) findViewById(R.id.title_text);
adapter =new ArrayAdapter(this,android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
zIqiweatherDB = ZIqiweatherDB.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).getCountyName();
Intent intent = new Intent(ChooseAreaActivity.this,WeatherActivity.class);
intent.putExtra("county_code",countyCode);
startActivity(intent);
finish();
}
}
});
queryProvince();//
}
/**
* , , 。
* @param
* @return
*/
private void queryProvince(){
provinceList = zIqiweatherDB.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");
}
}
/**
* , , 。
* @param
* @return
*/
private void queryCities(){
cityList = zIqiweatherDB.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");
}
}
/**
* , ,
* @param
* @return
*/
private void queryCounties(){
countyList = zIqiweatherDB.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
* @return
*/
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.handleProvinceResponse(zIqiweatherDB,response);
}else if ("city".equals(type)){
result=Utility.handleCitiesResponse(zIqiweatherDB,response,selectedProvince.getId());
}else if ("county".equals(type)){
result=Utility.handleCountiesResponse(zIqiweatherDB,response,selectedCity.getId());
}
if (result){
// runOnUiThread()
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)){
queryProvince();
}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();
}
});
}
});
}
/**
*
* @param
* @return
*/
private void showProgressDialog(){
if (progressDialog == null){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(" ...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
*
* @param
* @return
*/
private void closeProgressDialog(){
if (progressDialog != null){
progressDialog.dismiss();
}
}
/**
* back , , 、 、 。
* @param
* @return
*/
@Override
public void onBackPressed(){
if (currentLevel == LEVEL_COUNTY){
queryCities();
}else if (currentLevel == LEVEL_CITY){
queryProvince();
}else {
if (isFromWeatherActivity){
Intent intent = new Intent(this,WeatherActivity.class);
startActivity(intent);
}
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_choose_area, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
, 。
public class WeatherActivity extends AppCompatActivity implements View.OnClickListener {
// private LinearLayout weatherInfoLayout;
/**
*
*
* @param savedInstanceState
*/
private TextView cityNameText;
/**
*
*
* @param savedInstanceState
*/
private TextView publishText;
/**
*
*
* @param savedInstanceState
*/
private TextView weatherDespText;
/**
* 1
*
* @param savedInstanceState
*/
private TextView tempText;
/**
* 2
*
* @param savedInstanceState
*/
private TextView windText;
/**
*
*
* @param savedInstanceState
*/
private TextView currentDateText;
/**
*
*
* @param savedInstanceState
*/
private Button switchCity;
/**
*
*
* @param savedInstanceState
*/
private Button refreshWeather;
private String county = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
//
cityNameText = (TextView) findViewById(R.id.city_name);
publishText = (TextView) findViewById(R.id.publish_text);
weatherDespText = (TextView) findViewById(R.id.weather_text);
tempText = (TextView) findViewById(R.id.temp_text);
windText = (TextView) findViewById(R.id.wind_text);
currentDateText = (TextView) findViewById(R.id.date_text);
switchCity = (Button) findViewById(R.id.switch_button);
refreshWeather = (Button) findViewById(R.id.refresh_button);
String countyCode = getIntent().getStringExtra("county_code");
county = countyCode;
if (!TextUtils.isEmpty(countyCode)) {
//
publishText.setText(" ...");
cityNameText.setText(countyCode);
queryWeatherCode(countyCode);
} else {
//
showWeather();
}
switchCity.setOnClickListener(this);
refreshWeather.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.switch_button:
Intent intent = new Intent(this, ChooseAreaActivity.class);
intent.putExtra("from_weather_activity", true);
startActivity(intent);
finish();
break;
case R.id.refresh_button:
queryWeatherCode(county);
SimpleDateFormat formatter = new SimpleDateFormat ("MM dd HH:mm:ss ");
Date curDate = new Date(System.currentTimeMillis());//
String str = formatter.format(curDate);
publishText.setText(str+" ");
break;
default:
break;
}
}
/**
*
*/
private void queryWeatherCode(String countyCode) {
String address = "https://api.heweather.com/x3/weather?city=" + countyCode + "&key= key";
queryFromServer(address, "county_code");
}
/**
*
*/
private void queryFromServer(final String address, final String type) {
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
if (!TextUtils.isEmpty(response)) {
//
Utility.handleWeatherResponse(WeatherActivity.this, response);
runOnUiThread(new Runnable() {
@Override
public void run() {
showWeather();
}
});
}
}
@Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
publishText.setText(" ");
}
});
}
});
}
/**
* SharedPreferences ,
*/
private void showWeather() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
cityNameText.setText(preferences.getString("city_name", ""));
String temp = preferences.getString("temp1","")+"~"+preferences.getString("temp2","");
tempText.setText(temp);
String wind =preferences.getString("windDirection", "")+"--"+preferences.getString("windLevel","")+" ";
windText.setText(wind);
currentDateText.setText(preferences.getString("current_date", ""));
String weatherNow = preferences.getString("weather_now","");
String weatherNext= preferences.getString("weather_next", "");
if (weatherNow == weatherNext){
weatherDespText.setText(weatherNow);
}else {
weatherDespText.setText(weatherNow+" "+weatherNext);
}
}
}
, , JSON , sharedpreference , showlocation 。
。
API https://api.heweather.com/x3/weather?city=+ countyCode + "&key= key。 JSON 。
JSON 。
/**
* JSON ,
*/
public static void handleWeatherResponse(Context context,String response){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("HeWeather data service 3.0");
JSONObject newInfo = jsonArray.getJSONObject(0);
// basic
JSONObject basic = newInfo.getJSONObject("basic");
JSONArray daily_forecast = newInfo.getJSONArray("daily_forecast");
JSONObject condInfo = daily_forecast.getJSONObject(0);
JSONObject cond = condInfo.getJSONObject("cond");
JSONObject temp =condInfo.getJSONObject("tmp");
JSONObject wind =condInfo.getJSONObject("wind");
String cityName = basic.getString("city");
String weatherNow = cond.getString("txt_d");
String weatherNext = cond.getString("txt_n");
String temp1 = temp.getString("min");
String temp2 = temp.getString("max");
String windDirection = wind.getString("dir");
String windLevel =wind.getString("sc");
saveWeatherInfo(context,cityName,weatherNow,weatherNext,temp1,temp2,windDirection,windLevel);
} catch (JSONException e) {
e.printStackTrace();
}
}
private static void saveWeatherInfo(Context context, String cityName, String weatherNow,String weatherNext,String temp1,String temp2,String windDirection,String windLevel
) {
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_now", weatherNow);
editor.putString("weather_next",weatherNext);
editor.putString("temp1", temp1);
editor.putString("temp2", temp2);
editor.putString("windDirection",windDirection);
editor.putString("windLevel",windLevel);
editor.putString("current_date", sdf.format(new Date()));
editor.commit();
}
、 、 。 , JSON , JSON , , , 。