Android开发之Google天气显示(综合例子)

Android的google天气显示,包括读取网络信息,读取xml,使用网络信息二级制码生成文件

1.生成url
2.获取google返回的网络信息 new InputSource(aURL.openStream())
3.生成解析xml的处理器
4.解析xml
5.封装解析后的xml文件
6.根据解析后的数据,生成url,获取google返回的天气图标,赋值给图片

代码:

/*获取用户输入的城市名称*/
                String city = ((EditText) findViewById(R.id.input))
                    .getText().toString();
               
                /*组成URL字符串*/
                //中文:?hl=zh-cn&weather=
                //英文:?weather=
                String queryString = "http://www.google.com/ig/api?weather="
                    + city;
                /*将可能的空格替换为"%20"*/
                URL aURL = new URL(queryString.replace(" ", "%20"));
                                       
                /* 从SAXParserFactory获取SAXParser*/
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();

/* 从SAXParser得到XMLReader*/
                    XMLReader xr = sp.getXMLReader();

/*
                     * 创建GoogleWeatherHandler,以便解析XML内容
                     */
                    GoogleWeatherHandler gwh = new GoogleWeatherHandler();
                    xr.setContentHandler(gwh);

/* 解析XML文件内容 */
                    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() );
                   
                   
                    URL iconURL = new URL("http://www.google.com"+ gwh.getIconURL());
                URLConnection conn = iconURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    //设置icon
                    ImageView iv = (ImageView)findViewById(R.id.iconOfWeather);
                    Bitmap bm = null;
                    bm = BitmapFactory.decodeStream(bis);
                    iv.setImageBitmap(bm);
                    bis.close();
                    is.close();

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwygdd.html