这阶段要开始查询天气并把天气信息显示出来,天气信息应该需要在一个新的界面中显示出来,因此需要创建新的活动和布局文件
我们这里沿用的界面一如既往简单,代码如下所示:
<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">
<Button
android:id="@+id/switch_city"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
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:text="555"
android:textColor="#fff"
android:textSize="24sp"/>
<Button
android:id="@+id/refresh_weather"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="@drawable/refresh"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#27A5F9">
<TextView
android:id="@+id/publist_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textColor="#FFF"
android:text="111"
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:layout_gravity="center_horizontal"
android:gravity="center"
android:text="222"
android:textSize="18sp"
android:textColor="#FFF"
/>
<TextView
android:id="@+id/weather_desp"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="333"
android:textSize="40sp"
android:textColor="#FFF"
/>
<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:text="12"
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:textColor="#FFF"
android:text="-"
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:text="16"
android:textSize="40sp"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
这里两个Button下一阶段才需要使用的,所有可以暂时不管它
接着需要在Utility类中添加几个方法,用于解析和处理服务器返回的JSON数据,代码如下:
/*
* 解析服务器返回的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 publsihTime=weatherInfo.getString("ptime");
saveWeatherInfo(context,cityName,weatherCode,temp1,temp2,weatherDesp,publsihTime);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 将服务器返回的所有天气信息储存到SharePreferences文件中
*/
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("ciyt_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();
}
接下来该创建活动了,在activity包下新建WeatherActivity继承Activity,代码如下:
public class WeatherActivity extends Activity {
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);
//初始化各控件
weatherInfoLayout=(LinearLayout) findViewById(R.id.weather_info_layout);
cityNameText=(TextView) findViewById(R.id.city_name);
publishText=(TextView) findViewById(R.id.publist_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);
String countyCode=getIntent().getStringExtra("county_code");
if(!TextUtils.isEmpty(countyCode))
{
//有县级代号时就去查询天气
publishText.setText("同步中...");
weatherInfoLayout.setVisibility(View.INVISIBLE);
cityNameText.setVisibility(View.INVISIBLE);
queryWeatherCode(countyCode);
}else{
//没有县级代号就直接显示本地天气
showWeather();
}
}
/*
* 查询县级代号所对应的天气
*/
private void queryWeatherCode(String countyCode)
{
String address="http://www.weather.com.cn/data/list3/city"+countyCode+".xml";
queryFromServer(address,"countyCode");
}
/*
* 查询天气代号所对应的天气
*/
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.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
// TODO Auto-generated method stub
if("countyCode".equals(type))
{
if(!TextUtils.isEmpty(response))
{
//从服务器返回的数据中解析出天气代号
String[] array=response.split("\\|");
if(array!=null&&array.length==2)
{
String weatherCode=array[1];
queryWeatherInfo(weatherCode);
}
}
}else if("weatherCode".equals(type))
{
//处理服务器返回的天气信息
Utility.handleWeatherResponse(WeatherActivity.this, response);
runOnUiThread(new Runnable() {
public void run() {
showWeather();
}
});
}
}
@Override
public void onError(Exception e) {
// TODO Auto-generated method stub
runOnUiThread( new Runnable() {
public void run() {
publishText.setText("同步失败");
}
});
}
});
}
/*
* 从SharedPreferences文件中读取储存的天气信息,并显示到界面上。
*/
private void showWeather()
{
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
cityNameText.setText(prefs.getString("city_name", ""));
Log.i("info", prefs.getString("city_name",""));
temp1Text.setText(prefs.getString("temp1", ""));
temp2Text.setText(prefs.getString("temp1", ""));
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);
}
}
接下来我们要做的是从ChooseAreaActivity跳转到WeatherActivity了,修改一下ChooseAreaActivity中的代码,如下所示
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
isFromWeatherActivity=getIntent().getBooleanExtra("from_weather_activity", false);
//--------------增加项---------------------//
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("city_selected", false)&&!isFromWeatherActivity)
{
Intent intent=new Intent(this,WeatherActivity.class);
startActivity(intent);
finish();
return;
}
<pre name="code" class="java">public void onItemClick(AdapterView<?> arg0, View view, int index,
long arg3) {
// TODO Auto-generated method stub
if(currentLevel==LEVEL_PROVINCE)
{
selectedProvince=provinceList.get(index);
queryCities();
}else if(currentLevel==LEVEL_CITY)
{
selectedCity=cityList.get(index);
queryCounties();
}<pre name="code" class="java"> //--------------增加项---------------------//
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();}
可以看到,这里我们主要修改两处,第一在Oncreate方法的一开始先从SharedPreferences文件的city_selected标志位,如果是true的话就说明当前已经选择过城市了,第二,在OnItemclick()方法中再加入一个判断,如果当前的选级为LEVEL_COUNTY,就启动WeatherActivity,并把当前的县级代号传递过去。
还是和之前一样,不要忘记在AndroidManifest.xml文件中注册新的Activity活动
好了,如果前面的代码没错,现在运行下程序,然后选择江苏-苏州-昆山,结果如图所示
第三阶段的代码就编写到这里了,广告之后记得回来!