2017-09-29 60 views
0

所以,我有一個由JSON解析創建的ListView,我希望一旦從ListView中選擇一個項目被添加到另一個ArrayList,在那裏我使用HashMap,因爲它是一個數據包。問題是,如果我選擇一個它可以正常工作,但是一旦我選擇第二個,那麼我的ArrayList將會有第二個兩次,如果我再次執行第三個三等等。我附上下面的代碼部分,任何幫助將不勝感激。從列表視圖與HashMap創建ArrayList重複,而不是添加

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

       public void onItemClick(AdapterView<?> adapter, View v, int position, long id) { 

        Toast.makeText(getApplicationContext(), 
          "Bookmarked", 
          Toast.LENGTH_LONG) 
          .show(); 


//adding the data from the list view to the HashMap object 

        HashMap<String, String> obj = (HashMap<String, String>) adapter.getItemAtPosition(position); 
        String name = (String) obj.get("name"); 
        String rating = (String) obj.get("rating"); 
        String summary = (String) obj.get("summary"); 
        String date = (String) obj.get("publ. date"); 
        String type = (String) obj.get("type"); 
        String suggested_link = (String) obj.get("suggested_link_text"); 
        String link = (String) obj.get("link"); 


        bookmarked.put("rating", rating); 
        bookmarked.put("name", name); 
        bookmarked.put("summary", summary); 
        bookmarked.put("publ. date", date); 
        bookmarked.put("type", type); 
        bookmarked.put("suggested_link_text", suggested_link); 
        bookmarked.put("link", link); 


//the ArrayList that contains the HashMap data 
        selected.add(bookmarked); 

        Log.v("Selected: ", selected.toString()); 

       }}); 

回答

0

那是因爲你覆蓋的每次點擊的bookmarked對象,你每次添加此相同的對象添加到列表。 該解決方案是創建一個新的bookmarked對象每次:

HashMap<String, String> bookmarked = new HashMap<String, String>(); 
bookmarked.put("rating", rating); 
       bookmarked.put("name", name); 
       bookmarked.put("summary", summary); 
       bookmarked.put("publ. date", date); 
       bookmarked.put("type", type); 
       bookmarked.put("suggested_link_text", suggested_link); 
       bookmarked.put("link", link); 
+0

是定了!非常感謝!:) – doomspirospero

+0

@doomspirospero將它標記爲答案? – Neeraj

相關問題