2017-12-20 3 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); 
      } 

ログラインの下のコメントを参照してください。それは私が受け取る出力を説明します。 ArrayListの値をSimpleAdapter経由でListViewの2つのテキストフィールドに渡すにはどうすればよいですか?

はあなたにあなたが各反復で Mapに入れエントリー前の反復で置いエントリを置き換えることを意味 Listに同じ HashMapインスタンスを複数回追加する

+0

HashMapを試してみてくださいコード

以下のようなループの外で、あなたのneedsInfoViewlistviewにごneedsInfoAdapterを設定する必要がありますされ一意性のために設計されていて、以前に同じキーを追加しようとしている場合は、キー値を更新します –

答えて

1

が正しい値

を保持していない:

あなたは、各反復で新しいHashMapインスタンスを作成する必要がありますあなたのneedsInfoList

あなたまた、コードの下

ようなあなたのneedsInfoListリストに新しいインスタンスHashMapを追加するためのEDあなたはこの

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); 
    .... 
} 
関連する問題