android简单的天气预报例子和XML解析

main.xml
[html] view plaincopyprint?

    <?xml version="1.0" encoding="utf-8"?>  
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        android:orientation="vertical"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        >  
      
        <LinearLayout  
            android:layout_width="fill_parent"  
            android:layout_height="wrap_content"  
            android:orientation="horizontal"  
            >  
            <EditText  
            android:id="@+id/CityName"   
            android:layout_width="250dp"   
            android:layout_height="wrap_content"  
            android:layout_marginTop="2dip"  
            android:text="shenzhen">  
        </EditText>  
        <Button  
            android:id="@+id/ButtonGo"   
            android:layout_width="70dp"   
            android:layout_height="wrap_content"  
            android:layout_gravity="right|top"    
            android:text="go!go!">  
        </Button>  
        </LinearLayout>  
          
        <TextView    
            android:layout_width="fill_parent"   
            android:layout_height="fill_parent"   
            android:scrollbars="vertical"  
            android:background="#ffffff"  
            android:textColor="#000000"  
        android:id="@+id/infoText"  
        />      
    </LinearLayout>  


 weatherActivity.java
[html] view plaincopyprint?

    public class weatherActivity extends Activity {  
      
      
        private Button mButton = null;  
        private TextView mTextView = null;  
        private EditText mCityNameEdit = null;  
      
        final String DEBUG_TAG = "weather";  
      
        /** Called when the activity is first created. */  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.main);  
              
            mTextView = (TextView)findViewById(R.id.infoText);  
            mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());   
            mCityNameEdit = (EditText)findViewById(R.id.CityName);  
            mButton = (Button) findViewById(R.id.ButtonGo);  
            mButton.setOnClickListener(new Button.OnClickListener() {  
                public void onClick(View v) {                 
                    connect();                      
                }  
            });          
              
        }  
    }  


 

 1.连接网络,基于Http协议。

一般是发送请求到某个应用服务器。此时需要用到HttpURLConnection,打开连接,获得数据流,读取数据流。
   private void connect()  
    {  
    //http地址  
    //String httpUrl = "http://flash.weather.com.cn/wmaps/xml/shenzhen.xml";  
    String httpUrl = "http://flash.weather.com.cn/wmaps/xml/"+mCityNameEdit.getText().toString()+".xml";  
      
    String resultData = "";//获得的数据  
    URL url = null;  
    try  
    {  
        //构造一个URL对象  
        url = new URL(httpUrl);   
    }  
    catch (MalformedURLException e)  
    {  
        Log.e(DEBUG_TAG, "MalformedURLException");  
    }  
    if (url != null)  
    {  
        try  
        {  
            //使用HttpURLConnection打开连接  
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
            //得到读取的内容(流)  
            InputStreamReader in = new InputStreamReader(urlConn.getInputStream());  
            // 为输出创建BufferedReader  
            BufferedReader buffer = new BufferedReader(in);  
            String inputLine = null;  
            //使用循环来读取获得的数据  
            while (((inputLine = buffer.readLine()) != null))  
            {  
                //我们在每一行后面加上一个"\n"来换行  
                resultData += inputLine + "\n";  
            }           
            in.close();  
            urlConn.disconnect();  
            //设置显示取得的内容  
            if ( resultData != null )  
            {  
                mTextView.setText("");  
                weatherInfoXmlPullParser(resultData);//解析XML  
            }  
            else   
            {  
                mTextView.setText("读取的内容为NULL");  
            }  
        }  
        catch (IOException e)  
        {  
            Log.e(DEBUG_TAG, "IOException");  
        }  
    }  
    else  
    {  
        Log.e(DEBUG_TAG, "Url NULL");  
    }  
      }  

 

2.用PULL方式解析xml

PULL方式读xml会回调事件:

   读取到xml的声明返回      START_DOCUMENT;
   读取到xml的结束返回       END_DOCUMENT ;
   读取到xml的开始标签返回 START_TAG
   读取到xml的结束标签返回 END_TAG
   读取到xml的文本返回       TEXT

    public void weatherInfoXmlPullParser(String buffer){  
                  
        XmlPullParser xmlParser = Xml.newPullParser();//获得XmlPullParser解析器     
          
        ByteArrayInputStream tInputStringStream = null;  
        if (buffer != null && !buffer.trim().equals(""))  
        {  
           tInputStringStream = new ByteArrayInputStream(buffer.getBytes());  
        }  
        else  
        {  
            return ;  
        }  
      
        try   
        {  
            //得到文件流,并设置编码方式  
            //InputStream inputStream=mContext.getResources().getAssets().open(fileName);  
            //xmlParser.setInput(inputStream, "utf-8");  
            xmlParser.setInput(tInputStringStream, "UTF-8");  
              
            //获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。  
            int evtType=xmlParser.getEventType();  
               
            while(evtType!=XmlPullParser.END_DOCUMENT)//一直循环,直到文档结束     
            {   
                switch(evtType)  
                {   
                case XmlPullParser.START_TAG:  
                    String tag = xmlParser.getName();   
                    //如果是city标签开始,则说明需要实例化对象了  
                    if (tag.equalsIgnoreCase("city"))   
                    {   
                        weatherInfo info = new weatherInfo();   
                        //取出标签中的一些属性值  
                        info.setCityWeatherInfo(xmlParser);  
                        mTextView.append(info.getCityWeatherInfo()+"\n");  
                    }  
                    break;  
                   
                case XmlPullParser.END_TAG:  
                    //标签结束                     
                default:break;  
                }  
                //如果xml没有结束,则导航到下一个节点  
                evtType=xmlParser.next();  
            }  
        }   
        catch (XmlPullParserException e) {  
             // TODO Auto-generated catch block  
             e.printStackTrace();  
        }  
        catch (IOException e1) {  
             // TODO Auto-generated catch block  
             e1.printStackTrace();  
        }   
    }  


weatherInfo.java  

     public class weatherInfo{  
          
            static String cityname = "深圳";  
            static String stateDetailed ="多云转阵雨";  
            static String tem1 ="28";   
            static String tem2 ="22";   
            static String temNow ="25";  
            static String windState="微风";  
            static String windDir="北风";  
            static String windPower="2级";  
            static String humidity="63%";  
            static String time="10:30";  
              
            public void setCityWeatherInfo(XmlPullParser xmlParser)  
            {  
                cityname = xmlParser.getAttributeValue(null, "cityname");  
                stateDetailed = xmlParser.getAttributeValue(null, "stateDetailed");  
                tem1 = xmlParser.getAttributeValue(null, "tem1");  
                tem2 = xmlParser.getAttributeValue(null, "tem2");  
                temNow = xmlParser.getAttributeValue(null, "temNow");  
                windState = xmlParser.getAttributeValue(null, "windState");  
                windDir = xmlParser.getAttributeValue(null, "windDir");  
                windPower = xmlParser.getAttributeValue(null, "windPower");  
                humidity = xmlParser.getAttributeValue(null, "humidity");  
                time = xmlParser.getAttributeValue(null, "time");  
            }  
              
            public String getCityWeatherInfo()  
            {  
                String info = "所在城市:"+cityname + "\n"  
                    +"天气情况:"+stateDetailed + ", 湿度:" +humidity + "\n"  
                    +"现在气温:"+temNow + "°C, "+"最低:"+tem2 + "°C, "+"最高:"+tem1 + "°C\n"  
                    +"风情:"+windState +", 风向:"+windDir + ", 风力:"+windPower + "\n"                  
                    +"更新时间:"+time + "\n";  
                return info;  
            }  
      
    }  

猜你喜欢

转载自javaclubs.iteye.com/blog/1947892