Android实现天气查询

这里实现 省份–城市–天气 的联动。即先选择省份,再选择城市,最后展示天气信息。
思路:通过访问:http://www.webxml.com.cn/webservices/weatherwebservice.asmx,通过给定的方式获得所需要的数据,在方法中解析xml成list,然后展示即可。

1:布局与权限:

<uses-permission android:name="android.permission.INTERNET" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.inext.test.webview.WeatherActivity">

    <Spinner  android:id="@+id/pro" android:layout_width="match_parent" android:layout_height="wrap_content"></Spinner>
    <Spinner  android:id="@+id/city" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/pro" android:layout_alignParentStart="true"></Spinner>
    <ScrollView  android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/city" android:layout_alignParentStart="true">

        <TextView  android:id="@+id/show" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/city" android:layout_alignParentStart="true" />
    </ScrollView>
</RelativeLayout>

2:xml解析类,用于解析从站点返回的xml流,返回list:

/** * Created by Administrator on 2016/5/10. * 解析xml工具类 */
public class XMLUtil {
    private InputStream inputStream;
    public XMLUtil(InputStream inputStream){
        this.inputStream = inputStream;
    }

    //解析流成list
    public List getAllElement() throws XmlPullParserException, IOException {
        List list = null;
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(inputStream,"utf-8");
        //事件
        int eventType = xpp.getEventType();
        String elementName = "";
        //当事件不结束时
        while (eventType!=XmlPullParser.END_DOCUMENT){
            switch (eventType){
                //开始
                case XmlPullParser.START_DOCUMENT:
                    list = new ArrayList();
                    break;
                //开始一个标签
                case XmlPullParser.START_TAG:
                    //获得标签名称
                    elementName = xpp.getName();
                    break;
                //获得标签内容
                case XmlPullParser.TEXT:
                    if (elementName.equals("string")){
                        list.add(xpp.getText());
                    }
                    break;
                //标签结束
                case XmlPullParser.END_TAG:
                    break;
            }
            eventType = xpp.next();
        }
        return list;
    }
}

3:应用类:

public class WeatherActivity extends AppCompatActivity {

    private List list_city,list_pro,list_data;
    private Spinner pro,city;
    private TextView show;
    private  Context context = getBaseContext();
    private String cityName,proName,url_city,url_city_data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        pro = (Spinner)findViewById(R.id.pro);
        city = (Spinner)findViewById(R.id.city);
        show = (TextView)findViewById(R.id.show);
        //获取省份的地址
        String url_pro = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx/getSupportProvince";
        //执行获取省份的异步操作
        new MyAsync().execute(url_pro);


    }

    //获取省份。 城市和天气的获取与解析都是一样的思路
    public class MyAsync extends AsyncTask<String,Void,List>{

        @Override
        protected List doInBackground(String... params) {
            //调用getXml()方法,(该方法在本类底部位置)
            list_pro = getXml(params[0]);
            return list_pro;
        }

        @Override
        protected void onPostExecute(List list) {
            super.onPostExecute(list);
            if (list==null || list.size()==0){
                return;
            }
            Toast.makeText(getBaseContext(),""+list.size(),Toast.LENGTH_SHORT).show();
            ArrayAdapter arrayAdapter = new ArrayAdapter(getBaseContext(),android.R.layout.simple_dropdown_item_1line,list_pro);
            pro.setAdapter(arrayAdapter);
            pro.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    proName = pro.getSelectedItem().toString().trim();
                    //Toast.makeText(getBaseContext(),proName,Toast.LENGTH_SHORT).show();
                    url_city = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx/getSupportCity?byProvinceName="+proName;
                    new MyAsyncCity().execute(url_city);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

        }
    }
    //获取城市
    public class MyAsyncCity extends AsyncTask<String,Void,List>{

        @Override
        protected List doInBackground(String... params) {
            list_city = getXml(params[0]);
            return list_city;
        }

        @Override
        protected void onPostExecute(List list) {
            super.onPostExecute(list);
            if (list==null || list.size()==0){
                return;
            }
            //Toast.makeText(getBaseContext(),""+list.size(),Toast.LENGTH_SHORT).show();
            ArrayAdapter arrayAdapter = new ArrayAdapter(getBaseContext(),android.R.layout.simple_dropdown_item_1line,list_city);
            city.setAdapter(arrayAdapter);
            arrayAdapter.notifyDataSetChanged();
            city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    cityName = city.getSelectedItem().toString().trim();
                    cityName = cityName.split(" ")[0];
                    if (!city.equals("")){
                        url_city_data = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx/getWeatherbyCityName?theCityName="+cityName;
                        Toast.makeText(getBaseContext(),cityName,Toast.LENGTH_SHORT).show();
                        new MyWeather().execute(url_city_data);
                    }
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        }
    }

    public class MyWeather extends AsyncTask<String,Void,List>{

        @Override
        protected List doInBackground(String... params) {
            list_data = getXml(params[0]);
            return list_data;
        }

        @Override
        protected void onPostExecute(List list) {
            super.onPostExecute(list);
            StringBuilder sb = new StringBuilder();
            if (list_data.size()!=0 && list_data!=null){
                for (int i=0;i<list_data.size();i++){
                    String str = list.get(i).toString();
                    sb.append(str+"\n");
                }
                show.setText(sb.toString());
            }


        }
    }
    //getXml方法,解析获得流,并调用XMLUtil类解析流
    public List getXml(String urlString){
        List list = null;
        InputStream is = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(urlString);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setReadTimeout(5000);
            if (httpURLConnection.getResponseCode()==200){
                //获取返回的数据流
                is = httpURLConnection.getInputStream();
                //传入Xml解析工具类进行解析
                XMLUtil xmlUtil = new XMLUtil(is);
                try {
                    list = xmlUtil.getAllElement();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                }
            }else {
                Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
                return null;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (is!=null){
                    is.close();
                }

                if (httpURLConnection!=null){
                    httpURLConnection.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}

你可能感兴趣的:(Android实现天气查询)