案例3:实现天气预报

来源:互联网 发布:linux安装详解 编辑:程序博客网 时间:2024/05/18 00:51

一、实现效果图:

       


先来看看我的文件结构:


分析一下文件结构:

第一个包中放活动文件,adapter包是数据适配器包,moder包是定义 Weather 实体类封装所关心的信息,test包是测试类包,util包是工具类包。

因为这个案例的代码量大,因此这里只粘贴了部分代码。


二、主要代码:

1、java代码:

(1)WeatherActivity.java:

这部分代码是活动的主要实现代码,涉及到了多线程、动画、JSON数据解析以及网络的相关知识,实现起来难度较大。

package com.example.weather;/** * 1414110623 * @author 张钢 */import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import com.example.weather.R;import com.example.weather.adapter.WeatherAdapter;import com.example.weather.moder.Weather;import com.example.weather.util.HttpCallbackListener;import com.example.weather.util.HttpUtil;import com.google.gson.JsonArray;import com.google.gson.JsonObject;import com.google.gson.JsonParser;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.view.animation.LayoutAnimationController;import android.view.animation.ScaleAnimation;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ListView;import android.widget.Toast;public class WeatherActivity extends Activity {private EditText ecCity;private ImageButton btnQuery;private ListView lvFutureWeather;public static final int SHOW_RESPONSE = 1;private List<Weather> data;private Handler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case SHOW_RESPONSE:String response = (String) msg.obj;if (response != null) {parseWithJSON(response);WeatherAdapter weatherAdapter = new WeatherAdapter(WeatherActivity.this,R.layout.activity_weather_listitem, data);lvFutureWeather.setAdapter(weatherAdapter);ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0,1);scaleAnimation.setDuration(1000);LayoutAnimationController animationController = new LayoutAnimationController(scaleAnimation, 0.6f);lvFutureWeather.setLayoutAnimation(animationController);}break;default:break;}}private void parseWithJSON(String response) {// TODO Auto-generated method stubdata = new ArrayList<Weather>();JsonParser parser = new JsonParser();// json解析器JsonObject obj = (JsonObject) parser.parse(response);// 获取返回状态吗String resultcode = obj.get("resultcode").getAsString();// 状态码如果是200说明数据返回成功if (resultcode != null && resultcode.equals("200")) {JsonObject resultObj = obj.get("result").getAsJsonObject();JsonArray futureWeatherArray = resultObj.get("future").getAsJsonArray();for (int i = 0; i < futureWeatherArray.size(); i++) {Weather weather = new Weather();JsonObject weatherObject = futureWeatherArray.get(i).getAsJsonObject();weather.setDayOfWeek(weatherObject.get("week").getAsString());weather.setDate(weatherObject.get("date").getAsString());weather.setTemperature(weatherObject.get("temperature").getAsString());weather.setWeather(weatherObject.get("weather").getAsString());data.add(weather);}}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_weather);initViews();setListeners();}public void initViews() {ecCity = (EditText) findViewById(R.id.etCity);btnQuery = (ImageButton) findViewById(R.id.btnQuery);lvFutureWeather = (ListView) findViewById(R.id.lvFutureWeather);data = new ArrayList<Weather>();}private void setListeners() {btnQuery.setOnClickListener(new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubString cityName = ecCity.getText().toString();try {cityName = URLEncoder.encode(cityName, "utf-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}System.out.println("lvFutureWeather=" + lvFutureWeather);Toast.makeText(WeatherActivity.this, "success",Toast.LENGTH_LONG).show();String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="+ cityName + "&key=b6683508adf0adc07aa24e5cc0811487";Toast.makeText(WeatherActivity.this, "success" + weatherUrl,Toast.LENGTH_LONG).show();HttpUtil.sendHttpRequest(weatherUrl,new HttpCallbackListener() {public void onFinish(String response) {// TODO Auto-generated method stubMessage message = new Message();message.what = SHOW_RESPONSE;// 将服务器返回的结果存放到Message中message.obj = response.toString();handler.sendMessage(message);}public void onError(Exception e) {// TODO Auto-generated method stubSystem.out.println("访问失败");}});}});}}

(2)WeatherAdapter.java:

这部分代码是给主活动添加数据。

package com.example.weather.adapter;import java.util.List;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import com.example.weather.R;import com.example.weather.moder.Weather;public class WeatherAdapter extends ArrayAdapter<Weather> {private int resourceId;public WeatherAdapter(Context context, int textViewResourceId,List<Weather> objects) {super(context, textViewResourceId, objects);resourceId = textViewResourceId;}@Overridepublic View getView(int position, View convertView, ViewGroup viewgroup) {Weather weather = getItem(position);ViewHolder viewHolder = null;if (convertView == null) {viewHolder = new ViewHolder();convertView = LayoutInflater.from(getContext()).inflate(resourceId,null);viewHolder.tvDayOfWeek = (TextView) convertView.findViewById(R.id.tvDayofWeek);viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tvDate);viewHolder.tvTemperature = (TextView) convertView.findViewById(R.id.tvTemperature);viewHolder.tvWeather = (TextView) convertView.findViewById(R.id.tvWeather);convertView.setTag(viewHolder);} else {viewHolder = (ViewHolder) convertView.getTag();}viewHolder.tvDayOfWeek.setText(weather.getDayOfWeek());viewHolder.tvDate.setText(weather.getDate());viewHolder.tvTemperature.setText(weather.getTemperature());viewHolder.tvWeather.setText(weather.getWeather());return convertView;}private class ViewHolder {TextView tvDayOfWeek;TextView tvDate;TextView tvTemperature;TextView tvWeather;}}


(3)WeatherGetTest.java:

注意这部分代码给weatherUrl传入了一个密匙,申请密匙可到“聚合数据“”官网申请,每个人的密匙都不一样。申请密匙之后才能获取天气预报信息。

package com.example.weather.test;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import com.example.weather.util.HttpCallbackListener;import com.example.weather.util.HttpUtil;import android.test.AndroidTestCase;public class WeatherGetTest extends AndroidTestCase {public void testGetData() {String cityName = null;try {cityName = URLEncoder.encode(cityName, "utf-8");String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="+ cityName + "&key=b6683508adf0adc07aa24e5cc0811487";HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {public void onFinish(String response) {// TODO Auto-generated method stubSystem.out.println(response);}public void onError(Exception e) {// TODO Auto-generated method stub}});} catch (Exception e) {// TODO: handle exception}}}

2、布局文件:

(1)activity_weather.xml:

这部分代码是主界面的实现

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@drawable/city"    tools:context=".WeatherActivity" >    <LinearLayout        android:id="@+id/linearLayout1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <EditText            android:id="@+id/etCity"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_marginLeft="10dp"            android:layout_marginTop="20dp"            android:layout_weight="1"            android:background="@android:drawable/edit_text"            android:drawableLeft="@drawable/etcity"            android:drawablePadding="5dp"            android:ems="10"            android:hint="@string/etCity" >            <requestFocus />        </EditText>        <ImageButton            android:id="@+id/btnQuery"            android:layout_width="50dp"            android:layout_height="50dp"            android:layout_marginTop="20dp"            android:background="@null"            android:src="@drawable/serch" />    </LinearLayout>    <ListView        android:id="@+id/lvFutureWeather"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/linearLayout1"        android:layout_centerHorizontal="true"        android:layout_marginLeft="10dp"        android:layout_marginRight="10dp"        android:dividerHeight="10dp"        android:layoutAnimation="@anim/weather_list_layout_animation" >    </ListView></RelativeLayout>

(2)activity_weather_listitem.xml:

这部分代码是ListView的实现,即点击搜索按钮后,出现的一个带有一定格式的ListView界面。

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_margin="10dp"    android:background="@drawable/list_item_shape"    android:padding="10dp" >    <TextView        android:id="@+id/tvDayofWeek"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:layout_marginLeft="15dp"        android:text="星期日" />    <TextView        android:id="@+id/tvDate"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBaseline="@+id/tvDayofWeek"        android:layout_alignBottom="@+id/tvDayofWeek"        android:layout_alignParentRight="true"        android:text="20160207" />    <TextView        android:id="@+id/tvTemperature"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/tvDayofWeek"        android:layout_below="@+id/tvDayofWeek"        android:layout_marginTop="15dp"        android:text="temperature" />    <TextView        android:id="@+id/tvWeather"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/tvTemperature"        android:layout_below="@+id/tvTemperature"        android:layout_marginTop="15dp"        android:text="weather" /></RelativeLayout>

3、注册文件:

这里需要添加两个权限:

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

三、总结:

         做这个案例,遇到了很多问题,例如:导错包、程序闪退、相关控件不会用等问题,也学到了很多知识,例如动画制作、数据适配、添加网络访问权限、数据解析、多线程、LIstView控件的使用、获取天气信息等,收获颇多。


0 0