slgnalin
slgnalin

Reputation: 25

ListView will refresh already existing item and won't add a new one

I am trying to make a To Do List app and I have an EditText field where I enter the task. When I press the "add" floating action button the first task goes in the listview perfectly but when I try to add a second task, it will change the first task to the second and so on. So the thing is that I can only have on task at a time but what I want to have is a list of tasks.

This is my onCreate method, where I declare the floating action button and set an OnClickListener for it:

DBHelper dbHelper;
ArrayAdapter<String> mAdapter;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    // Finds you button from the xml layout file
    FloatingActionButton faButton = (FloatingActionButton) findViewById(R.id.fab);

    // Waits for you to click the button
    faButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Starts the function below
            addNotification();
            listView.setAdapter(mAdapter);
            addToDoElement(null);
        }
    });
    listView = (ListView)findViewById(R.id.lstTask);
}

And this is the method that adds the task from the EditText to the ListView

ArrayList<String> taskList;
public void addToDoElement(View view) {
    listView = (ListView) findViewById(R.id.lstTask);
    taskList = new ArrayList<>();
    mAdapter = new ArrayAdapter<String>(this, R.layout.row, R.id.task_title, taskList);

    listView.setAdapter(mAdapter);


    //Gets TASK text from EditText
    EditText mEdit   = (EditText)findViewById(R.id.titlu);
    Log.v("EditText", mEdit.getText().toString());

    taskList.add(mEdit.getText().toString());
    mEdit.setText("");
    mAdapter.notifyDataSetChanged();

}

Upvotes: 0

Views: 29

Answers (1)

tdelev
tdelev

Reputation: 863

The part where you initialize your taskList and mAdapter needs to be done only once, in your onCreate method. So move this block

listView = (ListView) findViewById(R.id.lstTask);
taskList = new ArrayList<>();
mAdapter = new ArrayAdapter<String>(this, R.layout.row, R.id.task_title, taskList);
listView.setAdapter(mAdapter);

in your onCreate method. Your current code is resetting the adapter and task list on each click event.

Upvotes: 1

Related Questions