import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class CurrentWeather extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button submit = (Button) findViewById(R.id.btn);
submit.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
/*从google上获得图标*/
try {
/*获取用户输入的城市名称*/
String city = ((EditText) findViewById(R.id.input))
.getText().toString();
/*组成URL字符串*//*将可能的空格替换为"%20"*/
//中文:http://www.google.com/ig/api?hl=zh-cn&weather=
//英文:http://www.google.com/ig/api?weather=
String queryString = "http://www.google.com/ig/api?weather="
+ city;
URL aURL = new URL(queryString.replace(" ", "%20"));
//parse the xml-file from the web site
GoogleWeatherHandler gwh = new GoogleWeatherHandler();
XMLReader xr = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
xr.setContentHandler(gwh);
xr.parse(new InputSource(aURL.openStream()) );
TextView tv1 = (TextView)findViewById(R.id.tem);
tv1.setText("温度:" + gwh.getCurrentTemp() + "摄氏度");
TextView tv2 = (TextView)findViewById(R.id.weather);
tv2.setText(gwh.getCurrentCondition());
TextView tv3 = (TextView)findViewById(R.id.hum);
tv3.setText(""+ gwh.getCurrentHum() );
//get the icon from the website
URL iconURL = new URL("http://www.google.com"+ gwh.getIconURL());
URLConnection conn = iconURL.openConnection();
conn.connect();
//start the stream
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
//how to set the icon from the bufferedInputStream
ImageView iv = (ImageView)findViewById(R.id.iconOfWeather);
iv.setImageBitmap(BitmapFactory.decodeStream(bis));
//end the stream
bis.close();
is.close();
} catch (Exception e) {
Log.e("error",e.toString());
}
}
});
}
}