2012-10-17 34 views
2

在激活中,我编写的代码可以正常工作。Android应用程序中ArrayList的OutOfMemoryError

但现在我已经添加了一个方法,以用下面的代码此活动:

private void obtenerDatosReuniones(){ 

    try { 

     int j=0; 

     String aux = jsonReuniones.getString("nombres"); 

     String aux2 = null; 

     aux2 = aux.replace("[", ""); 

     aux2= aux2.replace("]", ""); 

     String [] campos = aux2.split(","); 

     while(j<campos.length){ 

      nombres_reuniones.add(campos[j]); 

     } 

nombres_reunones的类型是ArrayList的

当运行该应用程序显示出在线路nombres_reuniones下面的错误。添加(campos [j]):

我在做什么错?

谢谢!

回答

3

看看你的循环:

while(j<campos.length){ 
    nombres_reuniones.add(campos[j]); 
} 

你如何预期不断整理?您不要修改j。既然你不进行任何更改j声明,并在一开始分配给它的0值后,这将是清晰的为:

​​

或者更好:

for (String item : campos) { 
    nombres_reuniones.add(item); 
} 

或者更简单:

nombres_reunions.addAll(Arrays.asList(campos)); 

另外,你刚才的代码可以更简单。看看这个:

String aux2 = null; 
aux2 = aux.replace("[", ""); 
aux2= aux2.replace("]", ""); 

何苦分配aux2null的初始值,你则立即覆盖?此外,您可以轻松链接方法调用。这将是整洁如:

String aux2 = aux.replace("[", "").replace("]", ""); 

而事实上,你可以链中的整个字符串处理一起,从开始到结束:

String[] campos = jsonReuniones.getString("nombres") 
           .replace("[", "") 
           .replace("]", "") 
           .split(","); 
nombres_reunions.addAll(Arrays.asList(campos)); 

(我停在那里,而不是内联即使这样表达......)

3

你不是推进循环:

​​

发生了什么事是,你加入“坎波斯”无限量的ArrayList,耗尽所有可用内存到您的处理程序。

请记住:循环的条件必须是false在循环结束的某个点。如果忘记提前循环(在这种情况下,通过增加j变量),条件将始终为true,循环将永不退出,因此会创建无限循环。

0

你没有更新的j值因此j总是0始终小于campos.length