2013-12-11 24 views
0

從listview中獲取特定鍵的值我面臨hashmap listview的getting all the value from specific key問題。我在這裏有兩個listview,第一個listview是顯示從數據庫獲得的數據,第二個listview是從第一個listview中獲取數據。現在,我希望從第二個列表視圖中獲取所有(FOODID3,itemID)的值以通過烤麪包顯示,但我只能獲取當前從第一個listview接收到的最新值。我認爲這個問題是因爲我在適配器上設置了notifyDataSetChanged。請幫忙!謝謝!如何使用條目

這是從數據庫

private void listMenu(String CID) 
{    
    ArrayList<Object> data = DB.getFood(CID); 

    LIST2 = new ArrayList<HashMap<String, String>>(); 

    for (int i=0; i<data.size(); i=i+4) 
    { 
     HashMap<String, String> map = new HashMap<String, String>(); 

     map.put(FOODID2, (String) data.get(i)); 
     map.put(FOODNAME2, (String) data.get(i+1)); 
     map.put(PRICE2, (String) data.get(i+2)); 
     map.put(RATING2, (String) data.get(i+3)); 

     LIST2.add(map); 
    } 

    LISTMENU = (ListView) findViewById(R.id.listMenu); 

    final List2Adapter adapter = new List2Adapter(MainActivity.this, LIST2); 
    LISTMENU.setAdapter(adapter); 


    LISTMENU.setOnItemClickListener(new OnItemClickListener() 
    { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
     { 

      HashMap<String, String> map = LIST2.get(position); 

      itemValue = map.get(FOODNAME2); 
      itemID = map.get(FOODID2); 

      Toast.makeText(getApplicationContext(), 
        "Food ID : " + itemID + "ListItem : " + itemValue , Toast.LENGTH_SHORT) 
        .show(); 

      listOrder(itemValue, itemID); 
     } 
    }); 
} 

獲取數據這是接收來自第一列表視圖中選擇的數據的第二列表視圖我的第一個列表視圖。

private void listOrder(String itemValue, String itemID) 
{ 
    HashMap<String, String> map = new HashMap<String, String>(); 

    String quantity = "1"; 

    map.put(FOODID3, itemID); 
    map.put(FOODNAME3, itemValue); 
    map.put(FOODQUANTITY3, quantity); 

    //problem is here, I can only display the latest data received 
    for(Entry<String, String> entry: map.entrySet()) 
    { 
     if(entry.getKey().equals(FOODID3)) 
     { 
      Toast.makeText(getApplicationContext(), 
      "EXISTS " + entry.getValue(), Toast.LENGTH_SHORT) 
      .show(); 
     } 
    } 

    LIST3.add(map); 

    LISTORDER = (ListView) findViewById(R.id.listOrder); 

    List3Adapter adapter = new List3Adapter(MainActivity.this, LIST3); 
    LISTORDER.setAdapter(adapter); 

    adapter.notifyDataSetChanged(); 

    LISTORDER.setOnItemClickListener(new OnItemClickListener() 
    { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
     { 

     } 
    }); 
} 
+2

映射不能包含給定鍵的多個值。 – njzk2

回答

2

地圖可以包含重複值不能包含重複鍵每次與現有鍵名稱添加元素

,它會覆蓋舊值與新

請通過Oracle Tutorials - Map

+0

我想我做錯了什麼,但無論如何,謝謝! – user3040029

+0

你想達到什麼目的? –

+0

其實我有這樣的問題非常類似的問題http://stackoverflow.com/questions/3900281/updating-list-hashmap 我想檢查從第一個列表視圖中選擇的itemID是否已經存在於第二個列表視圖中,數量++ 所以現在我仍然試圖通過使用toast來測試我從for循環得到的結果,從FOODID3的關鍵字獲取所有值 – user3040029

0

我不明白你想追加第三個食物項目到地圖嗎?如果是這樣,你應該重新初始化地圖,無論如何這是做錯的方法,你還應該創建一個Food對象並創建一個Food對象的HashMap,而不是將所有的key =>值放入它中。