繁体   English   中英

ArrayAdapter.notifyDataSetChanged()似乎不起作用

[英]ArrayAdapter.notifyDataSetChanged() does not seem to work

当我从List<T>添加或删除对象时,我调用myAdapter.notifyDataSetChanged()来“渲染” 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不会更新,但是当我关闭应用程序并重新运行它时,它包含了我创建的所有对象。

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

用新的对象实例化一个新的适配器,或者在适配器内部添加一个方法来更改数据。

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

customListAdapterCourse.add(your_new_data);

那么当您调用notifyDataSetChanged();时,实际上会有更改要注册notifyDataSetChanged();

customListAdapterCourse.notifyDataSetChanged();

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

customListAdapterCourse.loadObjects();

但是由于似乎您实际上是在将courses加载到适配器中,所以这可能不适用,因此最好使用add()

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

您还可以使用以下方法一次添加一堆商品:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM