Android实验九之天气预报

实验结果:

打开应用主页面:输入滨州

Android实验九之天气预报_第1张图片

Android实验九之天气预报_第2张图片

 

代码:

WeatherAtivity.java

package com.example.weather;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import model.Weather;
import Util.HttpCallbackListener;
import Util.HttpUtil;
import adapter.WeatherAdapter;
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;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class WeatherActivity extends Activity{

	private EditText etCity;
	private ImageButton btnQuery;
	private ListView lvFutureWeather;
	public static final int SHOW_PESPONSE = 1;
	private List data;
	
	
		private void parseWithJSON(String response){
			data = new ArrayList();
			JsonParser parser = new JsonParser();
			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;iactivity_weather.xml



    
        
           
           
        
        
        
    

    
    



activity_weather_listitem.xml



    
    
    
    
    



Weather.java

package model;

import android.R.string;

public class Weather {

	private String dayOfWeek;
	private String date;
	private String temperature;
	private String weather;
	public Weather(){
		
	}
	public Weather(String dayOfWeek,String date,String temperature,
			String weather){
		super();
		this.dayOfWeek = dayOfWeek;
		this.date = date;
		this.temperature = temperature;
		this.weather = weather;
	}
	public String getDayOfWeek() {
		return dayOfWeek;
	}
	public void setDayOfWeek(String dayOfWeek) {
		this.dayOfWeek = dayOfWeek;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public String getTemperature() {
		return temperature;
	}
	public void setTemperature(String temperature) {
		this.temperature = temperature;
	}
	public String getWeather() {
		return weather;
	}
	public void setWeather(String weather) {
		this.weather = weather;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "Weather[dayOfWeek="+dayOfWeek+",date="+date+",temperature="
				+temperature+",weather="+weather+"]";
	}
}


WeatherAdapter.java

package adapter;

import java.util.List;

import com.example.weather.R;

import model.Weather;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class WeatherAdapter extends ArrayAdapter{
	private int resourceId;	
	
	public WeatherAdapter(Context context, int textViewResourceId, List objects) {
		super(context, textViewResourceId, objects);
		resourceId = textViewResourceId;
	}

	public 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.tvDayOdWeek =  (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.tvDayOdWeek.setText(weather.getDayOfWeek());
		viewHolder.tvDate.setText(weather.getDate());
		viewHolder.tvTemperature.setText(weather.getTemperature());
		viewHolder.tvWeather.setText(weather.getWeather());
		return convertView;
	}

	private class ViewHolder{
		TextView tvDayOdWeek;
		TextView tvDate;
		TextView tvTemperature;
		TextView tvWeather;
	}
	

}


HttpCallbackListener.java

package Util;

public interface HttpCallbackListener {

	void onFinish(String response);
	void onError(Exception e);
}


HttpUtil.java

package Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.R.string;

public class HttpUtil {

	public static void sendHttpRequest(final String address,final HttpCallbackListener listener){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				HttpURLConnection connection = null;
				try {
					URL url = new URL(address);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setReadTimeout(8000);
					connection.setConnectTimeout(8000);
					connection.setDoInput(true);
					connection.setDoOutput(true);
					InputStream in = connection.getInputStream();
					BufferedReader reader = 
							new BufferedReader(new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line);
					}
					if(listener != null){
						//回调onfinish方法
						listener.onFinish(response.toString());
						
					}
				} catch (IOException e) {
					if(listener != null){
						listener.onError(e);
					}
					
				}finally {
					connection.disconnect();
				}
				
				
			}
		}).start();
	}
}


 

总结:

需要注意的两点:1、该应用中用到了JSON,所以应向libs中导入google的json-2.2.4.jar,才可以使用JSON解析器,对返回数据进行处理。2、该应用要从聚合网获得天气接口,要使用新申请的KEY。

 

案例3word的出现了一处错误,在WeatherActivity.java的onCreat方法中,应先定义各值调用setListener();然后再初始化UI调用initView();顺序颠倒则会出现空指针异常错误!

 

你可能感兴趣的:(android实验)