开发者

Why do I get duplicate Items in my ListView?

I'm using the following code to populate listview

Oncreate method:

SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.more_custom_row_view, new String[] {"title","desc"}, new int[] {R.id.text1,R.id.text2});
populateList();
setListAdapter(adapter);


static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); 

private void populateList() {
   HashMap<String,String> temp = new HashMap<String,String>();
   temp.put("title","Previous Searches");
   temp.put("desc", "View your search history");
   list.add(temp);
   HashMap<String,String> temp1 = new HashMap<String,String>();
   temp1.put("title","Settings");
   te开发者_JS百科mp1.put("desc", "Update your account settings");
   list.add(temp1);
}

when i go to another activity and come back to this acitivity it duplicate list items each time any one guide me what mistake am i doing?


The problem is that you are using a static list for your items and not clearing or reinstantiating it in your onCreate method.

The list will stay in memory as long as your program is running because it is defined static. If you are returning to the activity the items are again added to the list. You could use clear() to remove all items from the list in your populate list call before filling it again.


Simple, check adapter.isEmpty() before populating

This is a snippet from my own codebase.

private void populateWithAppPackages() {
  //DON'T continue if the adapter is not empty; prevents duplicates
  if(!mAdapter.isEmpty()){
    return;
  }

  /* ... populate the list ... */
}

DON'T clear() the list adapter!!

clear() and repopulating list every time the activity or the fragment are visited is a very expensive set of operations. You would be better of intelligently populating the list as above.


removing final from the list resolved my problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜