使用AsyncTask下载XML文件

时间:2012-05-02 12:48:51

标签: android android-asynctask httprequest

我一直在研究一个简单的天气应用程序 - 我正在使用Google Weather API。我正在尝试下载XML文件并根据其中的信息构建UI。

我尝试使用AsyncTask下载XML文件,然后解析它 - 但有些东西不起作用!当我运行代码时,我没有任何错误/应用程序启动但是xml文件中的信息没有显示!

以下是代码:

    package com.android.weatherApp;



public class WeatherAppActivity extends Activity {

    static String url="http://www.google.com/ig/api?weather=";
    static final String KEY_FORCAST_INFO="forcast_information";
    static final String KEY_CITY="city";
    static final String KEY_CURRENT_CONDITIONS="current_conditions";
    static final String KEY_CONDITION="condition";
    static final String KEY_TEMP="temp_c";
    static final String KEY_ICON_SRC="icon";
    static final String KEY_FORCAST_COND="forecast_conditions";
    static final String KEY_DAY_WEEK="day_of_week";
    static final String KEY_LOW_TEMP="low";
    static final String KEY_HIGH_TEMP="high";
    Document finalDoc;
    XMLParser xmlParser;
    private TextView currentWeather;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        downloadXMLFile task=new downloadXMLFile();
        task.execute("New+York");

    }

    private class downloadXMLFile extends AsyncTask<String,Void,String>
    {
        @Override
        protected String doInBackground(String... params) {

            String xml=null;

            try{
                DefaultHttpClient httpClient=new DefaultHttpClient();
                HttpPost httpPost=new HttpPost(url+params[0]);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity=httpResponse.getEntity();
                xml=EntityUtils.toString(httpEntity);

            }
            catch(UnsupportedEncodingException e)
            {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return xml;
        }

        @Override
        protected void onPostExecute(String xmlString)
        {
            Document doc = null;
            DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();

            try {
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is=new InputSource();

                is.setCharacterStream(new StringReader(xmlString));
                doc=db.parse(is);

            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            finalDoc=doc;

            NodeList nl=finalDoc.getElementsByTagName(KEY_CURRENT_CONDITIONS);
              NodeList nl2=finalDoc.getElementsByTagName(KEY_FORCAST_COND);
              currentWeather=(TextView)findViewById(R.id.currentState);
              TextView currentTemp = (TextView)findViewById(R.id.tempC);
              TextView currentLocation=(TextView)findViewById(R.id.currentLocation);
              currentLocation.setText("Iasi");

              for(int i=0;i<nl.getLength();i++)
              {
                Element e= (Element)nl.item(i);
                String cs=xmlParser.getValue(e, KEY_CONDITION).toUpperCase();
                currentWeather.setText(cs);

                String temperature=xmlParser.getValue(e, KEY_TEMP);
                currentTemp.setText(temperature);

                String logoImg=xmlParser.getValue(e, KEY_ICON_SRC).toLowerCase();

                if(logoImg.equals("/ig/images/weather/sunny.gif"))
                {
                    ImageView img=(ImageView)findViewById(R.id.wImg);
                    img.setImageResource(R.drawable.sun);
                }

              }

              for(int i=0;i<nl2.getLength();i++)
              {
                Element e=(Element)nl2.item(i);
                TextView day1=(TextView)findViewById(R.id.day1);
                day1.setText("TOMORW");
                TextView day2=(TextView)findViewById(R.id.day2);
                TextView day3=(TextView)findViewById(R.id.day3);
                ImageView img1=(ImageView)findViewById(R.id.day1Logo);
                ImageView img2=(ImageView)findViewById(R.id.day2Logo);
                ImageView img3=(ImageView)findViewById(R.id.day3Logo);
                TextView highTemp1=(TextView)findViewById(R.id.day1MaxTemp);
                TextView highTemp2=(TextView)findViewById(R.id.day2MaxTemp);
                TextView highTemp3=(TextView)findViewById(R.id.day3MaxTemp);

                String d1=xmlParser.getValue(e, KEY_DAY_WEEK).toUpperCase();
                String t=xmlParser.getValue(e, KEY_HIGH_TEMP); //get the max value of temperature - Fahrenheit
                int tempF=Integer.parseInt(t); // make the string a number
                float tC=(float) ((5./9)*(tempF-32)); // calculate the Celsius value of temperature
                tempF=(int)tC; // get only the Int value
                t=Integer.toString(tempF); // transform the temperature value back to string

                switch(i)
                {
                case 1:
                    highTemp1.setText(t);
                    break;
                case 2:
                    highTemp2.setText(t);
                    day2.setText(d1);
                    break;
                case 3:
                    highTemp3.setText(t);
                    day3.setText(d1);
                    break;
                }
              }
        }

    }

请你告诉我我做错了什么。 谢谢!

2 个答案:

答案 0 :(得分:2)

首先,您的网址变量包含“http://www.google.com/ig/api?weather=”而非“http://www.google.com/ig/api?weather=New+York”所以xml内容为空。

在doInBackground方法中尝试这样的事情:

String currentUrl = url; 
if(params.length>0 && params[0]!=null)currentUrl+= params[0];

我看到你在循环中实现了你的视图。您必须在onCreate方法或onStart方法中实例化它们。这样做,您将在创建活动后实例化这些变量,并获得性能。

答案 1 :(得分:0)

在您的清单中,您是否添加了<uses-permission android:name="android.permission.INTERNET"/>

您可以将Log.i("test",xmlString);放入onPostExecute并在日志中查看结果吗?