2013-12-07 80 views
0

所以我這樣做:把多個字符串到一個ArrayList

 int len = lv.getCount(); 

    List<String> Cool = null; 
    SparseBooleanArray checked = lv.getCheckedItemPositions(); 
    for (int i = 0; i < len; i++) 
     if (checked.get(i)) { 
      String item = String.valueOf(names.get(i)); 
      int start = item.lastIndexOf('=') + 1; 
      int end = item.lastIndexOf('}'); 
      String TEST = item.substring(start, end); 

      Log.d("Log", TEST); 

      Cool = new ArrayList<String>(); 

      Cool.add(TEST); 

     } 


      String NEW = StringUtils.join(Cool, ','); 

      Log.d("Log", NEW); 

哪個埃維時間替換與任何的下一個項目是列表中的事情。我如何讓它把字符串放在一起。

感謝您的幫助。

回答

1

你在每次迭代構建new ArrayList什麼你的for循環

Log.d("Log", TEST); 
Cool = new ArrayList<String>(); // NOT HERE!!!! 
Cool.add(TEST); 

構建一次,在循環外

List<String> Cool = new ArrayList<String>(); // also Cool should be cool. 
+0

沒有想到的是一個經過,感謝的快速反應 – MeIsOlsson

2
List<String> Cool = new ArrayList<String>(); 

創建頂部

Cool = new ArrayList<String>(); 

列表中刪除這條線,因爲它總是會創建一個新的列表,你不想

0

它不斷重置列表的原因是因爲您在循環中初始化列表。 在循環之外初始化它,該算法將工作。

初始化:

酷=新的ArrayList();

更正代碼:

int len = lv.getCount(); 

List<String> Cool = new ArrayList<String>(); 
SparseBooleanArray checked = lv.getCheckedItemPositions(); 
for (int i = 0; i < len; i++) 
    if (checked.get(i)) { 
     String item = String.valueOf(names.get(i)); 
     int start = item.lastIndexOf('=') + 1; 
     int end = item.lastIndexOf('}'); 
     String TEST = item.substring(start, end); 

     Log.d("Log", TEST); 

     Cool.add(TEST); 

    } 


     String NEW = StringUtils.join(Cool, ','); 

     Log.d("Log", NEW); 
相關問題