使用 AsyncTask 下载 XML 文件



我一直在开发一个简单的天气应用程序 - 我正在使用谷歌天气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;
                }
              }
        }
    }

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

首先,您的 url 变量包含"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 方法中实例化它们。这样,您将在创建活动后实例化这些变量,您将获得性能。

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

你能把Log.i("test",xmlString);放在你的 onPostExecute 中并在你的日志中查看结果吗?

最新更新