Search code examples
androidlistviewsugarorm

update listview on save


I have a code where I add all TODOs to the adapter, like this

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_todo);

     adapter = new TODOAdapter(this, TODO.listAll(TODO.class));
     listView = (ListView) findViewById(R.id.listView);
     listView.setAdapter(adapter);
    }

When add I new TODO, I do this

private void createTodo(String s) {
    TODOWorker.createTodo(s);
    adapter.notifyDataSetChanged();
    Toast.makeText(getApplicationContext(), "Your TODO was saved!", Toast.LENGTH_LONG).show();
}

but my listview is not beign updated...what am I missing?


Solution

  • My best guess after looking at your code is before calling notifyDatasetChanged() on your adapter you need to set the new list on the adapter. So when a new TODO is created add it to the list and update the list that the adapter is working with. Then call the notifyDatasetChanged()

    So let's say your adapter has a List<TODO> mDataList then you need to have a function like this

    public void setData(List<TODO> updatedList) {
        mDataList = new ArrayList<>(updatedList);
        notifyDataSetChanged();
    }
    

    and change your createToDo() to this

    private void createToDo(String s) {
        TODOWorker.createTodo(s);
        adapter.setData(TODO.listAll(TODO.class));
        Toast.makeText(getApplicationContext(), "Your TODO was saved!", Toast.LENGTH_LONG).show();
    }
    

    Hope this helps. I am assuming of course that your TODOWorker is not updating the list that the adapter is working with.