ArrayAdapter.notifyDataSetChanged()似乎不起作用

时间:2015-02-28 13:50:13

标签: java android

当我从List<T>添加或删除对象时,我将myAdapter.notifyDataSetChanged()称为&#34; rerender&#34; ListView,但它不起作用......

活动:

    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);

        //...

    }

适配器:

private Context context;
private List<Course> courses;

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

在其他活动中,我在数据库中以及onResume()

期间添加数据
@Override
    protected void onResume() {
        super.onResume();
        courses = getDataFromDatabase();
        customListAdapterCourse.notifyDataSetChanged();
    }

ListView未更新,但当我关闭应用并重新运行时,它包含我创建的所有对象。

2 个答案:

答案 0 :(得分:3)

您没有更新适配器的数据,只是更改对象的引用,但适配器中的引用指向旧对象。

使用新对象实例化新适配器或在适配器中添加方法以更改数据。

答案 1 :(得分:1)

您没有向适配器添加任何新数据。您需要致电.add()

customListAdapterCourse.add(your_new_data);

然后,当您致电notifyDataSetChanged();

时,实际上会有更改注册
customListAdapterCourse.notifyDataSetChanged();

根据您的适配器类型,您还可以使用loadObjects()来刷新数据。如果您知道已对数据库进行了更改并希望在数据集/列表视图中反映这些更改,则可能会导致对数据进行另一次查询(同样,取决于您的适配器类型)。如果您不需要使用add()remove()

,则可以使用此功能

customListAdapterCourse.loadObjects();

但是,由于看起来您实际上正在将courses加载到适配器中,这可能不适用,您最好使用add()

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

您还可以一次添加一堆项目:

customListAdapterCourse.addAll(array_of_new_objects);
customListAdapterCourse.notifyDataSetChanged();
相关问题