Reputation: 2907
I know that there are tons of questions like that. However, I tried them all and nothing helps me.
Thus, I have list of tasks. I store tasks in DB.
That's what I have in onCreate
taskDbHelper = new TaskDbHelper(getApplicationContext());
listView = (ListView) findViewById(R.id.listViewMainScreen);
final List<Task> list = taskDbHelper.getAllTasks();
taskListAdapter = new TaskListAdapter(this, list);
listView.setAdapter(taskListAdapter);
If user wants to delete one of tasks I have onLongClickListener for that.
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id)
{
Task task = list.get(position);
showEditDialog(task);
taskListAdapter.notifyDataSetChanged();
return true;
}
});
After that user see dialog fragment where he can confirm or cancel item delete.
If user chose to delete
taskDbHelper.deleteTask(getArguments().getString("task"));
MainScreen activity = (MainScreen) getActivity();
activity.onUpdate();
As you can see in MainACtivity I call method onUpdate
public void onUpdate()
{
taskListAdapter = new TaskListAdapter(this, taskDbHelper.getAllTasks());
((TaskListAdapter)listView.getAdapter()).notifyDataSetChanged();
}
And it doesn't work. I tried almost everything, but it worked only when I added to onUpdate
listView.setAdapter(taskListAdapter);
However, it looks like really bad solution to me. Maybe I am wrong ? And if not, what is the best way to do it?
Upvotes: 0
Views: 972
Reputation: 319
Remove the item from you list as well and don't initiate the adapter again.
list.remove(task);
((TaskListAdapter)listView.getAdapter()).notifyDataSetChanged();
Upvotes: 1