简单的天气预报 (五)

本篇完成的任务主要是在我们选定城市后,显示该城市的天气。

在第三篇中,我们提到的工具类Utility里有一个方法叫做handleWeatherResponse,它利用json解析天气数据的;还有一个方法叫做saveWeatherInfo,它利用SharedPreferences来保存天气数据的,具体的请去第三篇中去看。网址:http://blog.csdn.net/guya1990/article/details/42711171


先看看显示天气的ui



它的代码为:

<span style="font-family:Microsoft YaHei;font-size:18px;"><?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="50dip"
        android:background="#484e61" >

        <Button
            android:id="@+id/switch_city"
            android:layout_width="30dip"
            android:layout_height="30dip"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dip"
            android:background="@drawable/home" />

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

        <Button
            android:id="@+id/refresh_weather"
            android:layout_width="30dip"
            android:layout_height="30dip"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dip"
            android:background="@drawable/refresh" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dip"
        android:background="#99ccff" >

        <TextView
            android:id="@+id/publish_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dip"
            android:layout_marginTop="10dip"
            android:text="publish_text"
            android:textColor="#fff"
            android:textSize="18sp" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/weather_info_layout"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/current_date"
            android:layout_width="wrap_content"
            android:layout_height="40dip"
            android:gravity="center"
            android:text="current_date"
            android:textColor="#99cc33"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/weather_desp"
            android:layout_width="wrap_content"
            android:layout_height="60dip"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:text="weather_desp"
            android:textColor="#99cc33"
            android:textSize="40sp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="60dip"
            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_horizontal"
                android:text="temp1"
                android:textColor="#99cc33"
                android:textSize="40sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dip"
                android:layout_marginRight="10dip"
                android:text="~"
                android:textColor="#99cc33"
                android:textSize="40sp" />

            <TextView
                android:id="@+id/temp2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="temp2"
                android:textColor="#99cc33"
                android:textSize="40sp" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout></span>

代码很简单,由2个RelativeLayout组成。

第一个RelativeLayout里显示的是标题和两个按钮,两个按钮分别是刷新和重新选择城市。

第二个RelativeLayout里就是利用textView把我们json解析的内容放进去。


然后去实现逻辑代码。创建一个类:WeatherActivity,然后去清单文件里去注册一下。

在这个类中,我们主要完成以下几个任务。

mission1:

初始化ui代码里的控件

<span style="font-family:Microsoft YaHei;font-size:18px;">init();</span>
<span style="font-family:Microsoft YaHei;font-size:18px;">private void init() {
		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);

	}</span>

mission2:

获取天气代码

<span style="font-family:Microsoft YaHei;font-size:18px;">         /**
	 * 查询县级代号对应的天气代号
	 * 
	 * @param countyCode
	 */
	private void queryWeatherCode(String countyCode) {
		String address = "http://www.weather.com.cn/data/list3/city"
				+ countyCode + ".xml";
		queryFromServer(address, "countyCode");
	}</span>

获取联网地址,然后去调用queryFromServer()方法去查询县级天气代号。查询完后会回调queryWeatherInfo()方法。

mission3:

根据天气代码去查询天气

/**
	 * 查询天气代号对应的天气
	 * 
	 * @param weatherCode
	 */
	private void queryWeatherInfo(String weatherCode) {
		String address = "http://www.weather.com.cn/data/cityinfo/"
				+ weatherCode + ".html";
		queryFromServer(address, "weatherCode");
	}

讲县级天气代码拼接后,调用queryFromServer方法去联网查询天气。


<span style="font-family:Microsoft YaHei;font-size:18px;">	private void queryFromServer(final String address, final String type) {
		HttpUtil.sendRequest(address, new HttpCallbackListener() {

			@Override
			public void onFinish(final String response) {

				if (type.equals("countyCode")) {
					if (!TextUtils.isEmpty(response)) {
						// 从服务器返回的数据中解析出天气代号
						String[] array = response.split("\\|");
						if (array != null && array.length == 2) {
							String weatherCode = array[1];
							queryWeatherInfo(weatherCode);
						}
					}
				} else if (type.equals("weatherCode")) {
					// 处理服务器返回的天气信息
					Utility.handleWeatherResponse(WeatherActivity.this,
							response);

					runOnUiThread(new Runnable() {
						public void run() {
							showWeather();
						}
					});
				}
			}

			@Override
			public void onError(Exception e) {
				runOnUiThread(new Runnable() {
					public void run() {
						publishText.setText("同步失败");
					}
				});
			}
		});

	}</span>


联网查询完天气之后,我们去调用runOnUiThread回到主线程去显示天气。
mission4:

显示天气

<span style="font-family:Microsoft YaHei;font-size:18px;">/**
	 * 从sharedPreferences文件中读取天气信息,并且显示到界面上
	 */
	private void showWeather() {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(this);
		cityNameText.setText(sp.getString("city_name", ""));
		temp1Text.setText(sp.getString("temp1", ""));
		temp2Text.setText(sp.getString("temp2", ""));
		weatherDespText.setText(sp.getString("weather_desp", ""));
		publishText.setText("今天" + sp.getString("publish_time", "") + "发布");
		currentDateText.setText(sp.getString("current_date", ""));
		weatherInfoLayout.setVisibility(View.VISIBLE);
		cityNameText.setVisibility(View.VISIBLE);
	}</span>
调用本地sp里面的数据,显示天气。

自此,我们就大致描述完了显示天气的逻辑代码。下面给出全部代码。

package org.guya.myweather;

import org.guya.myweather.utils.HttpCallbackListener;
import org.guya.myweather.utils.HttpUtil;
import org.guya.myweather.utils.Utility;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WeatherActivity extends Activity implements OnClickListener {
	private LinearLayout weatherInfoLayout;

	/**
	 * 用于显示城市名字
	 */
	private TextView cityNameText;
	/**
	 * 用于显示发布时间
	 */
	private TextView publishText;
	/**
	 * 用于显示天气描述信息
	 */
	private TextView weatherDespText;
	/**
	 * 用于显示温度1
	 */
	private TextView temp1Text;
	/**
	 * 用于显示温度2
	 */
	private TextView temp2Text;
	/**
	 * 用于显示当前日期
	 */
	private TextView currentDateText;
	/**
	 * 切换城市按钮
	 */
	private Button switchCity;
	/**
	 * 更新天气按钮
	 */
	private Button refreshWeather;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.weather_layout);
		init();
		String countyCode = getIntent().getStringExtra("county_code");
		if (!TextUtils.isEmpty(countyCode)) {
			// 有县级代号就去查询天气
			publishText.setText("同步ing");
			weatherInfoLayout.setVisibility(View.INVISIBLE);
			cityNameText.setVisibility(View.INVISIBLE);
			queryWeatherCode(countyCode);
		} else {
			// 没有县一级的code,直接查询显示本地天气
			showWeather();
		}
		switchCity.setOnClickListener(this);
		refreshWeather.setOnClickListener(this);
	}

	private void init() {
		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);

	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.switch_city:
			Intent intent = new Intent(this, ChooseAreaActivity.class);
			intent.putExtra("from_weather_activity", true);
			startActivity(intent);
			finish();
			break;
		case R.id.refresh_weather:
			publishText.setText("同步ing...");
			SharedPreferences sp = PreferenceManager
					.getDefaultSharedPreferences(this);
			String weatherCode = sp.getString("weather_code", "");
			if (!TextUtils.isEmpty(weatherCode)) {
				queryWeatherInfo(weatherCode);
			}
			break;

		default:
			break;
		}

	}

	/**
	 * 查询县级代号对应的天气代号
	 * 
	 * @param countyCode
	 */
	private void queryWeatherCode(String countyCode) {
		String address = "http://www.weather.com.cn/data/list3/city"
				+ countyCode + ".xml";
		queryFromServer(address, "countyCode");
	}

	/**
	 * 查询天气代号对应的天气
	 * 
	 * @param weatherCode
	 */
	private void queryWeatherInfo(String weatherCode) {
		String address = "http://www.weather.com.cn/data/cityinfo/"
				+ weatherCode + ".html";
		queryFromServer(address, "weatherCode");
	}

	private void queryFromServer(final String address, final String type) {
		HttpUtil.sendRequest(address, new HttpCallbackListener() {

			@Override
			public void onFinish(final String response) {

				if (type.equals("countyCode")) {
					if (!TextUtils.isEmpty(response)) {
						// 从服务器返回的数据中解析出天气代号
						String[] array = response.split("\\|");
						if (array != null && array.length == 2) {
							String weatherCode = array[1];
							queryWeatherInfo(weatherCode);
						}
					}
				} else if (type.equals("weatherCode")) {
					// 处理服务器返回的天气信息
					Utility.handleWeatherResponse(WeatherActivity.this,
							response);

					runOnUiThread(new Runnable() {
						public void run() {
							showWeather();
						}
					});
				}
			}

			@Override
			public void onError(Exception e) {
				runOnUiThread(new Runnable() {
					public void run() {
						publishText.setText("同步失败");
					}
				});
			}
		});

	}

	/**
	 * 从sharedPreferences文件中读取天气信息,并且显示到界面上
	 */
	private void showWeather() {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(this);
		cityNameText.setText(sp.getString("city_name", ""));
		temp1Text.setText(sp.getString("temp1", ""));
		temp2Text.setText(sp.getString("temp2", ""));
		weatherDespText.setText(sp.getString("weather_desp", ""));
		publishText.setText("今天" + sp.getString("publish_time", "") + "发布");
		currentDateText.setText(sp.getString("current_date", ""));
		weatherInfoLayout.setVisibility(View.VISIBLE);
		cityNameText.setVisibility(View.VISIBLE);
	}
}

接下来就去是ChooseAreaActivity类里去添加Intent意图去跳转到显示天气的activity上。

分2个部分

1,如果之前,我们已经选择过了城市,那么就直接跳转到天气页面

SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(this);
		if (sp.getBoolean("city_selected", false)) {
			Intent intent = new Intent(this, WeatherActivity.class);
			startActivity(intent);
			finish();
			return;
		}

2,如果已经选择到了县级,那么就跳转到天气页面

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();
					Intent intent = new Intent(ChooseAreaActivity.this,
							WeatherActivity.class);
					intent.putExtra("county_code", countyCode);
					startActivity(intent);
					finish();

				}

			}
		});


运行程序,显示的结果是:








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值