Sean Courtney
Sean Courtney

Reputation: 41

How to add a new object to an already created list?

I'm trying to add a new object to a list that already starts 5 on the click of a button, but I'm having trouble accomplishing this in Android studio. This is my code to populate the list with the original 5.

private ArrayList<Course> populateList() {

    ArrayList<Course> list = new ArrayList<>();


    for (int i = 0; i < 5; i++) {
        Course course = new Course();
        list.add(course);
    }

    return list;
}

Upvotes: 0

Views: 790

Answers (3)

Sean Courtney
Sean Courtney

Reputation: 41

        addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Course course = new Course();
            list.add(course);
            courseAdapter.notifyDataSetChanged();
        }
    });

Upvotes: 0

mostafa zaghloul
mostafa zaghloul

Reputation: 65

to add any item just write

listName.add(object);

but if you speak about listview or any recycler you should notify every change by

Adapter.notifyDataSetChanged();

Upvotes: 1

Ridcully
Ridcully

Reputation: 23655

You just need to do this once again per button click.

Course course = new Course();
list.add(course);

If you're showing the list in a RecyclerView or ListView, you need to call notifyDatasetChanged in order for the view to refresh the list and show the new item.

Upvotes: 1

Related Questions