獲取天氣預報及相關xml解析 android開發,代碼片段

来源:互联网 发布:php return exit 编辑:程序博客网 时间:2024/06/05 11:55

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());
    }

   }

  });

 }
}  

原创粉丝点击