【问题标题】:How to update ListView with new table data?如何用新的表格数据更新 ListView?
【发布时间】:2013-11-26 19:07:53
【问题描述】:

我正在尝试使用以下方法:

protected void onCreate(Bundle savedInstanceState) {
    ...
    recordsCursor = dbHelper.fetchRecords1();
    startManagingCursor(recordsCursor);
    String[] from = new String[]{DbAdapter.KEY_BL_SENDER, DbAdapter.KEY_BL_READ};
    int[] to = new int[]{R.id.text1, R.id.background};   
    adapter = new SimpleCursorAdapter(this, R.layout.row, recordsCursor, from, to);
    setListAdapter(adapter);
}

public boolean onOptionsItemSelected(MenuItem item) {
...
case R.id.list1:
    recordsCursor = dbHelper.fetchRecords1();
    String[] fromBL = new String[]{DbAdapter.KEY_BL_SENDER, DbAdapter.KEY_BL_READ};
    int[] toBL = new int[]{R.id.text1, R.id.background};   
    Log.i(TAG, "count: "+recordsCursor.getCount()); // returns 475
    adapter = new SimpleCursorAdapter(this, R.layout.row, recordsCursor, fromBL, toBL);
    adapter.changeCursor(recordsCursor);
    adapter.notifyDataSetChanged();
    return true;

case R.id.list2:
    recordsCursor = dbHelper.fetchRecords2();
    String[] from = new String[]{DbAdapter.KEY_W_SENDER};
    int[] to = new int[]{R.id.text1};
    Log.i(TAG, "count: "+recordsCursor.getCount()); // returns 0
    adapter = new SimpleCursorAdapter(this, R.layout.row, recordsCursor, from, to);
    adapter.changeCursor(recordsCursor);
    adapter.notifyDataSetChanged();
    return true;

但它不会更新列表。一旦显示来自fetchRecords1 的记录,它们就不会被另一个表中的记录替换。我的代码有什么问题?

【问题讨论】:

  • 您在哪里将此适配器归于您的列表?
  • @Dyna,我已经更新了我的代码以反映它
  • @blahdiblah 给你的答案会解决你的问题!

标签: android android-listview android-cursoradapter android-cursor


【解决方案1】:

最快的改变是在你的 switch 中去掉这些行:

adapter.changeCursor(recordsCursor);
adapter.notifyDataSetChanged();

并将它们替换为:

setListAdapter(adapter);

当您将适配器设置为新的 SimpleCursorAdapter 时,它不会传播回 ListView。 ListView 仍然具有对使用 setListAdapter 设置的原始适配器的引用,而您的新适配器未连接到任何 ListView。

更优雅的变化是调用changeCursorAndColumns

case R.id.list2:
    recordsCursor = dbHelper.fetchRecords2();
    String[] from = new String[]{DbAdapter.KEY_W_SENDER};
    int[] to = new int[]{R.id.text1};
    Log.i(TAG, "count: "+recordsCursor.getCount()); // returns 0
    adapter.changeCursorAndColumns(recordsCursor, from, to);
    adapter.notifyDataSetChanged();
    return true;

另请注意,自 API 11 起,the constructor you're using 已被弃用:

此构造函数在 API 级别 11 中已弃用。
不鼓励使用此选项,因为它会导致在应用程序的 UI 线程上执行游标查询,从而可能导致响应速度不佳甚至应用程序无响应错误。作为替代方案,将 LoaderManager 与 CursorLoader 一起使用。

【讨论】:

  • 非常感谢。我尝试使用setListAdapter,但在切换回list1 后失败了。但它适用于changeCursorAndColumns
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多