@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
//对spinner赋值
private void init()
{
Spinner city_spr = (Spinner) findViewById(R.id.Spinner01);//取得xml中的按钮
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, ConstData.city);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
city_spr.setAdapter(adapter);//放上去
Button submit = (Button) findViewById(R.id.Button01);//确认按钮
//设置它的监听
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Spinner spr = (Spinner) findViewById(R.id.Spinner01);
Long l = spr.getSelectedItemId();//被选择项的id
int index = l.intValue();
String cityParamString = ConstData.cityCode[index];//得到城市代码
String str = "http://www.weather.com.cn/data/cityinfo/"+cityParamString+".html";
str=getWebContent(str);
try {
JSONObject json;
String str1 = null,str2 = null,str3 = null;
json=new JSONObject(str).getJSONObject("weatherinfo");
str1=json.getString("city");
str2=json.getString("temp1");
str3=json.getString("weather1");
TextView tex1=(TextView)findViewById(R.id.city_name);
tex1.setText(str1);
///tex1.setText("1");
TextView tex2=(TextView)findViewById(R.id.wind);
tex2.setText(str2);
//tex2.setText("2");
TextView tex3=(TextView)findViewById(R.id.temp);
tex3.setText(str3);
//tex3.setText("3");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
public String getWebContent(String url) {
//创建一个http请求对象
HttpGet request = new HttpGet(url);
//创建HttpParams以用来设置HTTP参数
HttpParams params=new BasicHttpParams();
//设置连接超时或响应超时
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 5000);
//创建一个网络访问处理对象
HttpClient httpClient = new DefaultHttpClient(params);
try{
//执行请求参数项
HttpResponse response = httpClient.execute(request);
//判断是否请求成功
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//获得响应信息
String content = EntityUtils.toString(response.getEntity());
return content;
} else {
//网连接失败,使用Toast显示提示信息
}
}catch(Exception e) {
e.printStackTrace();
} finally {
//释放网络连接资源
httpClient.getConnectionManager().shutdown();
}
return null;
}