实验_天气

运行效果图:



下载gson.jar 复制到项目libs文件夹里。


新建WeatherAdapter.java:

package cn.example.d4_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 cn.example.R;
import cn.example.d4_model.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;
	}

	@Override
	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.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;
	}
}
新建Weather.java:

package cn.example.d4_model;

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()
	{
		return "Weather [dayOfWeek=" + dayOfWeek + ", date=" + date + ", temperature=" + temperature + ", weather="
				+ weather + "]";
	}
}
新建HttpCallbackListener.java:

package cn.example.d4_uiti;

public interface HttpCallbackListener
{
	void onFinish(String response);

	void onError(Exception e);
}

新建类HttpUtil.java.xml
package cn.example.d4_uiti;

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

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.setConnectTimeout(8000);
					connection.setReadTimeout(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 (Exception e)
				{
					if (listener != null)
					{
						// 回调onError()方法
						listener.onError(e);
					}
				} finally
				{
					if (connection != null)
					{
						connection.disconnect();
					}
				}
			}
		}).start();
	}
}

MainAcvitity.java的代码:

package cn.example;

import java.util.ArrayList;
import java.util.List;

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 cn.example.d4_adapter.WeatherAdapter;
import cn.example.d4_model.Weather;
import cn.example.d4_uiti.HttpCallbackListener;
import cn.example.d4_uiti.HttpUtil;


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

public class MainActivity extends Activity
{
	private EditText etCity;
	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(android.os.Message msg)
		{
			switch (msg.what)
			{
			case SHOW_RESPONSE:
				String response = (String) msg.obj;
				if (response != null)
				{
					parseWithJSON(response);
					WeatherAdapter weatherAdapter = new WeatherAdapter(MainActivity.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);
				}
			default:
				break;
			}
		}

		private void parseWithJSON(String response)
		{
			data = 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);
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initViews();
		setListeners();
	}

	private void initViews()
	{
		etCity = (EditText) findViewById(R.id.etCity);
		btnQuery = (ImageButton) findViewById(R.id.btnQuery);
		lvFutureWeather = (ListView) findViewById(R.id.lvFutureWeather);
	}

	private void setListeners()
	{
		btnQuery.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View view)
			{
				String city = etCity.getText().toString();
				System.out.println("lvFutureWeather=" + lvFutureWeather);
				Toast.makeText(MainActivity.this, "success", Toast.LENGTH_LONG).show();
				String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="+city+"&key=e8c930b90b9dbe8b529deb14f3bf1c0f";
				HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener()
				{
					@Override
					public void onFinish(String response)
					{
						Message message = new Message();
						message.what = SHOW_RESPONSE;
						// 将服务器返回的结果存放到Message 中
						message.obj = response.toString();
						handler.sendMessage(message);
					}

					@Override
					public void onError(Exception e)
					{
						System.out.println("访问失败");
					}
				});
			}
		});
	}
}



acvitity_main.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/activity_weather_bg"
    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/icons_weather_city"
            android:drawablePadding="5dp"
            android:ems="10"
            android:hint="请输入你要查询的城市天气" >

            <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/icons_weather_query" />
    </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>
新建activity_weather_listitem.xml:

<?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>





Android天气预报实验报告模板 public class SetCityActivity extends Activity { //定义的一个自动定位的列表 private ListView gpsView; //定义的一个省份可伸缩性的列表 private ExpandableListView provinceList; //定义的用于过滤的文本输入框 private TextView filterText; //定义的一个记录城市码的SharedPreferences文件名 public static final String CITY_CODE_FILE="city_code"; //城市的编码 private String[][] cityCodes; //省份 private String[] groups; //对应的城市 private String[][] childs; //自定义的伸缩列表适配器 private MyListAdapter adapter; //记录应用程序widget的ID private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.set_city); gpsView = (ListView)findViewById(R.id.gps_view); provinceList= (ExpandableListView)findViewById(R.id.provinceList); //设置自动定位的适配器 gpsView.setAdapter(new GPSListAdapter(SetCityActivity.this)); //==============================GPS================================= //当单击自动定位时 gpsView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView localeCity = (TextView)view.findViewById(R.id.locateCityText); localeCity.setText("正在定位..."); final LocateHandler handler = new LocateHandler(localeCity); //添加一个线程来处理定位 new Thread(){ public void run() { Map<Integer, String> cityMap= getLocationCityInfo(); //记录匹配的城市的索引 int provinceIndex = -1; int cityIndex = -1; //传给处理类的数据封装对象 Bundle bundle = new Bundle(); if(cityMap!=null) { //得到图家名 String country = cityMap.get(LocationXMLParser.COUNTRYNAME); //只匹配中国地区的天气 if(country!=null&&country.equals("中国")){ //得到省 String province = cityMap.get(LocationXMLParser.ADMINISTRATIVEAREANAME); //得到市 String city = cityMap.get(LocationXMLParser.LOCALITYNAME); //得到区县 String towns = cityMap.get(LocationXMLParser.DEPENDENTLOCALITYNAME); Log.i("GPS", "============"+province+"."+city+"."+towns+"=============="); //将GPS定位的城市与提供能查天气的城市进行匹配 StringBuilder matchCity = new StringBuilder(city); matchCity.append("."); matchCity.append(towns); //找到省份 for(int i=0; i<groups.length; i++) { if(groups[i].equals(province)) { provinceIndex = i; break; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值