为什么我的for循环不执行?

时间:2014-08-19 13:31:51

标签: java android

在我的try块中,我有一个for循环,我确定它不起作用,因为当我登录for循环时,我没有得到任何回复意义在我的应用程序中循环未被访问。

这是我的try块,其中包含for循环:

try 
        {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();

            if (response == HttpURLConnection.HTTP_OK) 
            {
                anInStream = httpConn.getInputStream();
                InputStreamReader in= new InputStreamReader(anInStream);
                BufferedReader bin= new BufferedReader(in);

                String line = new String();
                while (( (line = bin.readLine())) != null)
                {

                    result = result + line;
                }
            }

                    menuItems = new ArrayList<HashMap<String, String>>();
                    Log.v(TAG, "index1=" + menuItems);

                    Handler parser = new Handler();
                    String xml = result; // getting XML
                    Document doc = parser.getDomElement(xml);

                    NodeList nl = doc.getElementsByTagName(KEY_FUEL);
                    Log.v(TAG, "index2=" + nl);

                    for (int i = 0; i < nl.getLength(); i++) 
                    {
                        Log.v(TAG, "index3=" + nl);

                        HashMap<String, String> map = new HashMap<String, String>();
                        Element e = (Element) nl.item(i);

                        map.put(KEY_HIGHEST, parser.getValue(e, KEY_HIGHEST));
                        map.put(KEY_AVERAGE, parser.getValue(e, KEY_AVERAGE));
                        map.put(KEY_LOWEST, parser.getValue(e, KEY_LOWEST));
                        map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
                        Log.v(TAG, "index4=" + map);

                        menuItems.add(map);
                        Log.v(TAG, "index5=" + menuItems);
                    }
        }
        catch (IOException ex) 
        {
            try 
            {
                throw new IOException("Error connecting");
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
         }
        return menuItems;

我添加了捕获并返回完整性,也许这些是原因。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您检查过您的NodeList是否为空?如果getElementsByTagName调用返回一个空列表,那么它的长度将为0,并且将跳过for循环,因为在第一次迭代之前将满足终止条件。尝试记录nl的长度。