Android的 - notifyDataSetChanged()不工作 [英] Android - notifyDataSetChanged() not working

查看:125
本文介绍了Android的 - notifyDataSetChanged()不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了显示问题清单自定义ArrayAdapter。我查询数据库,转换数据,将数据传递到一个数组,然后将数组传递给一个Ar​​rayAdapter来显示我的列表。

I have created a custom ArrayAdapter that displays a list of questions. I query the db, transform that data, pass the data to an array, and then pass the array to the ArrayAdapter to display my list.

dbData = getDbData();
List<Question> questions = getQuestions(1L);
dbData.closeDb();
setContentView(R.layout.activity_questions);
adapter = new QuestionsAdapter(this, getCurrentContext(), questions, 1L, dbData);

在我的应用程序,你可以再点击各种问题,处理一些东西,回来的主列表。底层数组还没有发生变化,因为变化已经在数据库被保留。我再次查询数据库,运行我转换,然后我的数组是最新的。我这样做,我的 onResume()方法,但适配器不会承认任何变化 notifyDataSetChanged()方法。我的 onResume()是这样的:

In my app, you can then click on the various question, manipulate some stuff and come back to the main list. The underlying array has not yet changed, because the changes have been persisted in the db. I again query the db, run my transformations, and then my array is up to date. I do this in my onResume() method, but the adapter won't recognize any changes with the notifyDataSetChanged() method. My onResume() looks like this:

@Override
protected void onResume() {
    super.onResume();
    dbData = getDbData();
    questions = getQuestions(1L);
    adapter = new QuestionsAdapter(this, getCurrentContext(), questions, 1L, dbData);
    items.setAdapter(adapter);
}

我要查询数据库,使变革,创造我的数组,然后创建一个新的适配器为我的变化显示在主列表上。为什么我不能只是做:

I have to query the db, make the transformations, create my array, and then create a new adapter for my changes to show up on the main list. Why can't I just do:

@Override
protected void onResume() {
    super.onResume();
    dbData = getDbData();
    questions = getQuestions(1L);
    adapter.notifyDataSetChanges();
}

我需要什么做的,使这项工作?感谢您的帮助。

What do I need to do to make this work? Thanks for the help.

推荐答案

这是适配器保留所有元素的副本,所以,当你调用notifyDataSetChanged,它会检查自己的元素的副本

An adapter keeps a copy of all the elements, so when you call notifyDataSetChanged, it checks its own copy of the elements

请尝试以下操作:

@Override
protected void onResume() {
    super.onResume();
    dbData = getDbData();
    questions = getQuestions(1L);

    adapter.clear();
    adapter.addAll(questions);  // API level [1..10] use for(..){ adapter.add(question.get(index)) }  or simply implement addAll method in you custom adapter for your own convenience (thanks to @Mena)
    adapter.notifyDataSetChanged();
}

这篇关于Android的 - notifyDataSetChanged()不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆