2017-12-20 5 views
0

놀랍게도 작동하지 않는 다음 코드가 있습니다.Hashmap에서 ArrayList 로의 루프가 올바른 값을 보유하고 있지 않습니다. 어떻게 고치는 지?

 needsInfoView = (ListView) findViewById(R.id.needsInfo); 
      needsInfoList = new ArrayList<>(); 
      HashMap<String, String> needsInfoHashMap = new HashMap<>(); 

      for (int i = 0; i < 11; i++) { 
       needsInfoHashMap.put("TA", needsTitleArray[i]); 
       needsInfoHashMap.put("IA", needsInfoArray[i]); 
       Log.e("NIMH",needsInfoHashMap.toString()); 
//Here, I get the perfect output - TA's value, then IA's value 
       needsInfoList.add(needsInfoHashMap); 
       Log.e("NIL",needsInfoList.toString()); 
//This is a mess - TA, IA values for 12 entries are all the same, they are the LAST entries of needsTitleArray and needsInfoArray on each ArrayList item. 

       needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList, 
         R.layout.needsinfocontent, new String[]{ "TA", "IA"}, 
         new int[]{R.id.ta, R.id.ia}); 
       needsInfoView.setVerticalScrollBarEnabled(true); 
       needsInfoView.setAdapter(needsInfoAdapter); 
      } 

로그 라인 아래의 주석을 참조하십시오. 그게 제가받는 결과물을 설명합니다. SimpleList를 통해 ListList의 두 텍스트 필드에 ArrayList 값을 전달하는 방법은 무엇입니까?

는 당신에게 당신이 각 반복에 Map에 넣어 항목 이전 반복에 의해 넣어 항목을 대체를 의미 List, 동일한 HashMap 인스턴스를 여러 번 추가

+0

의 HashMap가 시도하여 needsInfoAdapter 코드 아래

같은 루프 밖에서 needsInfoViewlistview로 설정해야합니다 코드를 아래처럼 needsInfoList 목록에 새로운 인스턴스 HashMap를 추가합니다 고유성을 위해 설계되었으며 이전 키와 동일한 키를 추가하려는 경우 키 값을 업데이트합니다 –

답변

1

올바른 값

유지되지 않습니다

각 반복에 대한 새로운 HashMap 인스턴스를 생성해야합니다 귀하의 needsInfoList

당신은 에드

는 또한

needsInfoList = new ArrayList<>(); 
needsInfoView = (ListView) findViewById(R.id.needsInfo); 

    for (int i = 0; i < 11; i++) { 
     HashMap<String, String> needsInfoHashMap = new HashMap<>(); 
     needsInfoHashMap.put("TA", needsTitleArray[i]); 
     needsInfoHashMap.put("IA", needsInfoArray[i]); 
     needsInfoList.add(needsInfoHashMap); 
    } 
    needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList, 
       R.layout.needsinfocontent, new String[]{"TA", "IA"}, 
       new int[]{R.id.ta, R.id.ia}); 
    needsInfoView.setVerticalScrollBarEnabled(true); 
    needsInfoView.setAdapter(needsInfoAdapter); 
0

감사드립니다. 당신이에서 같은 인스턴스 HashMap으로 추가되기 때문에 ArrayList-Hashmap의 루프를 들어

for (int i = 0; i < 11; i++) { 
    HashMap<String, String> needsInfoHashMap = new HashMap<>(); 
    needsInfoHashMap.put("TA", needsTitleArray[i]); 
    needsInfoHashMap.put("IA", needsInfoArray[i]); 
    needsInfoList.add(needsInfoHashMap); 
    .... 
} 
관련 문제