private void searchWeather(String city) {
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
XMLReader reader = sp.getXMLReader();
XmlHandler handler = new XmlHandler();
reader.setContentHandler(handler);
URL url = new URL("" + URLEncoder.encode(city));
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is,"GBK");
InputSource source = new InputSource(isr);
reader.parse(source);
List weatherList = handler.getWeatherList();
TableLayout table = (TableLayout)findViewById(R.id.table);
table.removeAllViews();
for(Weather weather : weatherList) {
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
row.setGravity(Gravity.CENTER_VERTICAL);
ImageView img = new ImageView(this);
img.setImageDrawable(loadImage(weather.getImageUrl()));
img.setMinimumHeight(80);
row.addView(img);
TextView day = new TextView(this);
day.setText(weather.getDay());
day.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(day);
TextView temp = new TextView(this);
temp.setText(weather.getLowTemp() + "℃ - " + weather.getHighTemp() + "℃");
temp.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(temp);
TextView condition = new TextView(this);
condition.setText(weather.getCondition());
condition.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(condition);
table.addView(row);
}
} catch (Exception e) {
new AlertDialog.Builder(this)
.setTitle("解析错误")
.setMessage("获取天气数据失败,请稍候再试。")
.setNegativeButton("确定", null)
.show();
}
}