java - ArrayAdapter.notifyDataSetChanged() 似乎不起作用

标签 java android

当我从 List<T> 添加或删除对象时,我调用myAdapter.notifyDataSetChanged() “重新渲染”ListView ,但它不起作用...

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

        //...

    }

适配器:

private Context context;
private List<Course> courses;

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

在其他 Activity 中,我在数据库中添加数据,并在 onResume() 期间添加数据。 :

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

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

最佳答案

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

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

关于java - ArrayAdapter.notifyDataSetChanged() 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28782445/

相关文章:

java - 在JFrame中添加图像,点击时图像

java - Spring在所有 Controller 方法中执行一个方法而不注入(inject)服务

java - SpringMVC + Spring Security Hibernate + Thymeleaf - 我的 pom.xml 太多了吗?

android - Kotlin-allopen for android

java - Angular5中的日期格式错误

java - 添加带有 spring security 的自定义登录 Controller

android - 指示在 Datatable Flutter 上选择的项目数的文本

android - Cordova/Phonegap 获取设备的电话号码 (Android & iOS)

java.lang.RuntimeException : Unable to start activity ComponentInfo:android. view.InflateException

java - 安卓和Java : Edit Text with multiple language support but few special characters