I know there are already a lot of questions pertaining to this same issue.
Mine looks a bit weird! I have a custom adapter for ListView where I pass an ArrayList of a Model. I have a Context Menu set for this List where on clicking delete, I need to delete the row from ListView (refreshing then and there).
I am calling xxxxx.remove(info.position)
and then listadapter.notifyDataSetChanged()
, but it duplicates the last row that was present in the ListView.
Here's the code:
Adapter for ListView:
class MyAdapter extends ArrayAdapter {
private final Context context;
private final ArrayList<ListModel> itemsArrayList;
public MyAdapter(Context context, ArrayList<ListModel> itemsArrayList) {
super(context, R.layout.viewlistitems, itemsArrayList);
this.context = context;
this.itemsArrayList = itemsArrayList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Get rowView from inflater
rowView = inflater.inflate(R.layout.viewlistitems, parent, false);
}
else
rowView = convertView;
// 3. Get the two text view from the rowView
TextView listNameView = (TextView) rowView.findViewById(R.id.listName);
listNameView.setTypeface(ViewListActivity.segoe);
listDateView.setTypeface(ViewListActivity.openSansLightIt);
String listName1 = itemsArrayList.get(position).getListName();
String listName2 = listName1.substring(0,1).toUpperCase() + listName1.substring(1);
listNameView.setText(listName2);
return rowView;
}
}
ContextMenu:
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.ListView01) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(todoItems.get(info.position).getListName());
String[] menuItems = {"Delete"};
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
if(item.getTitle().equals("Delete")) {
Toast.makeText(this,
todoItems.get(info.position).getListName() + " deleted!",
Toast.LENGTH_SHORT).show();
todoItems.remove(info.position);
//newList.invalidateViews();
adapter.notifyDataSetChanged();
}
return true;
}
Unable to fix this bug since 1 day! Any idea why this could be happening or what's causing it?
Many thanks!
Alright, I finally resolved this.
I used notifyDataSetInvalidated()
to invalidate the current adapter, and set a new adapter with my modified list. Worked fine.