Android天气预报

emptoney 2013-03-27

1.Android的天气预报的应用还是挺多的,基于JSON和WebServ的均可。首先我们来介绍基于JSON解析的天气预报的开发

2.这需要寻找到合适的数据源。这里使用的是http://www.weather.com.cn/(中央气象局)的数据信息。可通过m.weather.com.cn/data/101010100.html或者www.weather.com.cn/data/cityinfo/101010100.html。

查看到北京的天气信息

3.接下来就是对JSON数据的解析

```

packagecom.cater.weather;

importjava.io.IOException;

importorg.apache.http.HttpResponse;

importorg.apache.http.HttpStatus;

importorg.apache.http.client.ClientProtocolException;

importorg.apache.http.client.HttpClient;

importorg.apache.http.client.methods.HttpGet;

importorg.apache.http.impl.client.DefaultHttpClient;

importorg.apache.http.util.EntityUtils;

importorg.json.JSONException;

importorg.json.JSONObject;

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.widget.EditText;

importandroid.widget.TextView;

publicclassWeatherReportActivityextendsActivity

{

privatefinalstaticStringurl="http://m.weather.com.cn/data/101010100.html";

privateHttpClienthttpClient;

privateHttpResponsehttpResponse;

privateHttpGethttpGet;

privateEditTexteditText;

privateTextViewtextView;

privateStringtoday;

privateStringdayofweek;

privateStringcity;

privateintftime;

privateStringtemplate;

@Override

publicvoidonCreate(BundlesavedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

editText=(EditText)findViewById(R.id.editText1);

textView=(TextView)findViewById(R.id.textView1);

httpClient=newDefaultHttpClient();

parseString(getRequest(url));

editText.setText(getRequest(url));

textView.setText("城市:"+city+"\n"

+"温度:"+template+"\n"

+"星期:"+dayofweek+"\n"

+"时间:"+ftime+"\n"

+"日期:"+today+"\n");

}

privateStringgetRequest(Stringuri)

{

httpGet=newHttpGet(uri);

Stringresult="";

try

{

httpResponse=httpClient.execute(httpGet);

if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)

{

result=EntityUtils.toString(httpResponse.getEntity());

returnresult;

}

}

catch(ClientProtocolExceptione)

{

e.printStackTrace();

}

catch(IOExceptione)

{

e.printStackTrace();

}

returnnull;

}

privateStringparseString(Stringstr)

{

try

{

JSONObjectjsonObject=newJSONObject(str).getJSONObject("weatherinfo");

today=jsonObject.getString("date_y");

dayofweek=jsonObject.getString("week");

city=jsonObject.getString("city");

ftime=jsonObject.getInt("fchh");

template=jsonObject.getString("temp1");

}

catch(JSONExceptione)

{

e.printStackTrace();

}

returnnull;

}

}

相关推荐

大树 / 0评论 2011-09-29