利用json获取天气信息


       天气预报信息获取是利用json获取的,网上有非常多资源,源码。因为上面涉及到非常多天气信息,包含湿度,出行建议等,以及加入了全部城市代码的资源包。为了练手了解json的原理。我仅获取诚笃城市的最高温,最低温,城市名字。

     我的布局是通过一个button获取城市名字,最高温,最低温。main.xnl代码例如以下

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="城市名称:" />

    <EditText
        android:id="@+id/tx_cityname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="最高温度:" />

    <EditText
        android:id="@+id/tx_height"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="最低温度:" />

    <EditText
        android:id="@+id/tx_low"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />
	 <Button
        android:id="@+id/button_refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="获取实时天气信息" >
    </Button>
</LinearLayout>

     本project含有2个java文件各自是WheatherLck.java和WheatherInfo.java文件。WheatherLck.java代码例如以下

package com.hiden.weatherdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;







import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class WeatherLck extends Activity {

	// 创建三个全局的文本框对象
		EditText TX_CITYNAME,TX_HEIGHT,TX_LOW;
		private String city_str="成都";
		Button button_refresh;
		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
			setContentView(R.layout.main);
			
			// 获取布局中的文本框
			TX_CITYNAME=(EditText)this.findViewById(R.id.tx_cityname);
			TX_CITYNAME.setText(city_str);
			TX_HEIGHT=(EditText)this.findViewById(R.id.tx_height);
			TX_LOW=(EditText)this.findViewById(R.id.tx_low);
			
			button_refresh=(Button)findViewById(R.id.button_refresh);
			
			button_refresh.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(v==button_refresh){
						refresh(city_str);
					}
					
				}
			});
		

		/**************************************************************************************
		 * 获取http://m.weather.com.cn/data/101091106.html上面的数据
		 * 当中101091106为城市代码,上面我已经把城市代码做了改动,去除了空行,格式为UTF-8
		 * 每次仅仅是执行一次线程,然后增加主线程回收
		 * @param city_str
		 * @throws JSONException 
		 * @throws Exception 
		 * @throws ClientProtocolException 
		 */
		private Thread thread;
		private Handler handler = new  Handler(){
			@Override
			public void handleMessage(Message msg){
				switch(msg.what){
				case 1:
					JSONObject weather = (JSONObject) msg.obj;
					refreshUI(weather);
					try {
						thread.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				}
			}
		};
		/************************************************************************
		 * 在主线程中不能请求网络
		 * 线程没有while循环仅仅是执行一次,假设有溢出可能不能发送消息
		 * @param city_str
		 */
		private void requestWeather(final String city_str){
			
			thread = new Thread(new Runnable(){
				@Override
				public void run() {
					// TODO Auto-generated method stub

				
					String url="http://www.weather.com.cn/data/cityinfo/101270101.html";
					HttpClient client = new DefaultHttpClient();
					HttpGet httpget = new HttpGet(url);
					HttpResponse response;
					String sbuf = null;
					try {
						response = client.execute(httpget);
						HttpEntity httpentity = response.getEntity();	
						if(httpentity != null){
							BufferedReader br = new BufferedReader(new InputStreamReader(httpentity.getContent(),"utf-8"));	
							sbuf = br.readLine();	
						}	
						JSONObject object = new JSONObject(sbuf);
						JSONObject data = (JSONObject) object.getJSONObject("weatherinfo");
						//Log.i(TAG, data.toString());
						Message msg = new Message();
						msg.what = 1;
						msg.obj = data;
						handler.sendMessage(msg);
						
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}	
			});
			thread.start();
			
		}
		protected void refresh(String city_str)
		{
			requestWeather(city_str);
		}
		private void refreshUI(JSONObject jsonobject){
			
			JSONObject jsonData = jsonobject;
			try
			{
				
				TX_CITYNAME.setText(jsonData.getString("city"));
				// 取得高温数据
				TX_HEIGHT.setText(jsonData.getString("temp1"));
				// 取得低温数据
				TX_LOW.setText(jsonData.getString("temp2"));

			
			}catch(Exception e){
				e.printStackTrace();
			}

		}

	}



     WheatherInfo.java代码例如以下:

package com.hiden.weatherdemo.ui;

public class WeatherInfo {
	String city = "";
	String temp1 = "";
	String temp2 = "";// 椋庡悜


	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	@Override
	public String toString() {
		return "WeatherInfo [city=" + city + ", temp1=" + temp1
				+ ", temp2=" + temp2 + "]";
	}

	

	public String getTemp1() {
		return temp1;
	}

	public void setTemp1(String temp) {
		this.temp1 = temp;
	}
	
	public String getTemp2() {
		return temp2;
	}

	public void setTemp2(String temp) {
		this.temp2 = temp;
	}


}
点击button,获得到成都的最高温度和最低温度,效果图例如以下:

当然,大家能够依据自己的需求做出更具体的效果图,比方加入未来5天的天气,定位,加入关注城市等功能。网上资源比較多,大家能够多练习练习。



原文地址:https://www.cnblogs.com/mengfanrong/p/3927980.html