将数组赋值给另一个数组时抛出异常

时间:2011-08-30 10:38:46

标签: java android

我有一个获取某个网站HTML代码的功能。最终该函数将整个页面作为数组返回。我试图将页面保存在另一个数组中,但由于某种原因它总是会抛出异常(ArrayIndexOutOfBoundsException)。

我不确定我是否只是缺少一些基本的东西,或者它不仅仅是那个。给你一些我的代码:

  protected String[] doInBackground(String... login)
        {
            String[] page = new String[1024];
            try {
                page = executeHttpGet(); //THIS IS WHERE IT FAILS
            } catch (Exception e) {
                page[0] = "Error";
            }
            return page;
        }

public String[] executeHttpGet() throws Exception {
         URL u;
         InputStream is = null;
         DataInputStream dis;
         String s;
         int i = 0;
         String[] page = new String[1024];
         addSecurityException();
         Authenticator.setDefault(new MyAuthenticator(activity));
         try {
            u = new URL("https://myurl.com");
            is = u.openStream();        
            dis = new DataInputStream(new BufferedInputStream(is));
            while ((s = dis.readLine()) != null) {
                if (s.toString().length() > 10)
                    {
                    page[i] = s.toString();
                    i++;
                    }
            }
        } catch (IOException ioe) {

        }
         finally {
            try {
               is.close();
            } catch (IOException ioe) {

            }
        } 
         return page;
    }
    }

有没有人知道为什么我无法将返回的数组分配给doInBackground()中的数组?非常感谢帮助。

1 个答案:

答案 0 :(得分:7)

  1. 你的捕获块是空的,这是一个可怕的想法,因为当出现问题时你会得到没有信息。
  2. 当您在下面重新分配两行时,您不需要在其声明上初始化page(您必须更改catch - 块以创建新数组,'虽然)。
  3. 您是否检查过您的网址返回的行数不超过1024行?
  4. s.toString()s时,您不需要String,因为它只会返回s
  5. 在分析异常时,您应该查看整个堆栈跟踪,找出完全出现问题的位置。
  6. 询问有关异常时,您应发布整个堆栈跟踪!
  7. 当您有一个未指定数量的元素List时,它是一种更灵活,更易于使用的数组替代方案。一般来说,数组是非常低级的,并且几乎没有理由直接使用它们(它们对构建 List实现非常有用。