@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;
}
有什麼錯誤?
試了一下,返回的json string是
{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"3℃","temp2":"-6℃","weather":"晴轉多雲","img1":"d0.gif","img2":"n1.gif","ptime":"08:00"}}
沒有weather1,應該是weather