標籤:android blog http java os io 檔案 資料
天氣預報資訊擷取是利用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;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif(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(){@Overridepublic 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 blocke.printStackTrace();}break;}}};/************************************************************************ * 在主線程中不能請求網路 * 線程沒有while迴圈僅僅是執行一次,假設有溢出可能不能發送訊息 * @param city_str */private void requestWeather(final String city_str){thread = new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubString 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.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;}@Overridepublic 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天的天氣,定位,加入關注城市等功能。網上資源比較多,大家能夠多練習練習。