【问题标题】:notifyDataSetChanged() not working in ListFragmentnotifyDataSetChanged() 在 ListFragment 中不起作用
【发布时间】:2012-03-27 03:13:14
【问题描述】:

我在通过数据库查询填充的ListFragment 中有一个ListView。当它第一次填充onCreate() 中的列表时,它会很好地加载所有数据。但是当我重新查询数据库时,将返回值分配给assignmentsCursor,并调用notifyDataSetChanged(),它不会更新adapter.mCursor。如果我在 Eclipse 中进入调试模式,我可以看到 assignmentsCursor.mCount 发生了变化,但是当我查看 adapter.mCursor.mCount 时,它和以前一样。 (是的,我正在检查 notifyDataSetChanged() 已被调用。)

我的代码的相关部分:

SimpleCursorAdapter adapter;
Cursor assignmentsCursor;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        course = savedInstanceState.getShort(Values.ASSIGNMENT_KEY_COURSE);
    }
    setRetainInstance(true);

    // Create and array to specify the fields we want
    String[] from = new String[] { Values.KEY_TITLE, Values.ASSIGNMENT_KEY_COURSE };

    // and an array of the fields we want to bind in the view
    int[] to = new int[] { R.id.assignment_list_title, R.id.assignment_list_course };

    // Need to give assignmentsCursor a value -- null will make it not work
    updateAdapter();

    adapter = new SimpleCursorAdapter(context, R.layout.assignment_list_item, assignmentsCursor, from, to);
    setListAdapter(adapter);
}

public void onResume() {
    super.onResume();
    updateAdapter();
    refresh();
}

/**
 * Updates the content in the adapter.
 */
public void updateAdapter() {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean showingCompleted = sharedPrefs.getBoolean(Values.ASSIGNMENT_KEY_SHOWING_COMPLETED, false);

    if (course < 0) // Showing assignments from all courses
        if (showingCompleted)
            assignmentsCursor = DbUtils.fetchAllAssignments(context, Values.ASSIGNMENT_LIST_FETCH, null, true);
        else
            assignmentsCursor = DbUtils.fetchIncompleteAssignments(context, Values.ASSIGNMENT_LIST_FETCH, null, true);
    else // Showing assignments from specified course
        if (showingCompleted)
            assignmentsCursor = DbUtils.fetchAllAssignments(context, Values.ASSIGNMENT_LIST_FETCH, course, true);
        else
            assignmentsCursor = DbUtils.fetchIncompleteAssignments(context, Values.ASSIGNMENT_LIST_FETCH, course, true);

}

private void refresh() {
    updateAdapter();
    adapter.notifyDataSetChanged();
}

帮帮我!! ;)

附:如果您需要更多详细信息/代码,请告诉我。我很肯定数据库正在正确查询。

【问题讨论】:

  • 新光标已创建但从未使用过。 adapter.changeCursor(...?
  • 是的,我想这就是你的做法!我找了一个 setCursor(),但我想 changeCursor() 就是我要找的!我觉得自己好傻。 (一巴掌)非常感谢!

标签: java android simplecursoradapter android-listfragment


【解决方案1】:

感谢 Deucalion,我确定我错误地认为适配器引用了 assignmentsCursor 变量,而不是为自己创建了光标的副本。我需要做的只是调用adapter.changeCursor(assignmentsCursor) 以便它更新其本地副本。再次感谢杜卡利翁!

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多