BnJ
BnJ

Reputation: 1044

ArrayAdapter.notifyDataSetChanged() does not seem to work

When I add or remove object from a List<T>, I call myAdapter.notifyDataSetChanged() to "rerender" the ListView, but it does not work...

Activity:

    private ListView lv_course; //Liste des matières
    private List<Course> courses = new ArrayList<Course>();
    private CustomListAdapterCourse customListAdapterCourse;

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

        courses = getDataFromDatabase();

        lv_course = (ListView) findViewById(R.id.lv_course);
        customListAdapterCourse = new CustomListAdapterCourse(this, courses);
        lv_course.setAdapter(customListAdapterCourse);

        //...

    }

Adapter:

private Context context;
private List<Course> courses;

public CustomListAdapterCourse(Context theContext, List<Course> theListCourses) {
    super(theContext, 0, theListCourses);
    this.context = theContext;
    this.courses = theListCourses;
}

In an other activity, I add data in database, and during the onResume() :

@Override
    protected void onResume() {
        super.onResume();
        courses = getDataFromDatabase();
        customListAdapterCourse.notifyDataSetChanged();
    }

The ListView is not updated, but when I close the app and rerun it, it contains all objects I have created.

Upvotes: 0

Views: 79

Answers (2)

Max Worg
Max Worg

Reputation: 2972

You aren't adding any new data to your adapter. You need to call .add()

customListAdapterCourse.add(your_new_data);

then there will actually be changes to register when you call notifyDataSetChanged();

customListAdapterCourse.notifyDataSetChanged();

Depending on your adapter type you can also use loadObjects() to cause a refresh of your data. This may cause another query to be made for data (again, depending on your adapter type) if you are aware that a change has been made to a database and would like to reflect those changes in your dataset/listview. This would be used if you don't require the use of add() or remove()

customListAdapterCourse.loadObjects();

But since it appears that you are actually loading courses into the adapter this might not apply and you are better off with add().

customListAdapterCourse.add(your_new_data_row);
customListAdapterCourse.notifyDataSetChanged();

You can also add a bunch of items at once with:

customListAdapterCourse.addAll(array_of_new_objects);
customListAdapterCourse.notifyDataSetChanged();

Upvotes: 1

user3629714
user3629714

Reputation:

You're not updating your adapter's data, you're just changing the reference to the object, but the reference in your adapter points to the older object.

Either instantiate a new adapter with the new object or add a method inside your adapter to change your data.

Upvotes: 3

Related Questions