我正在尝试使用以下方法:
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
的记录,它们就不会被另一个表中的记录替换。我的代码出了什么问题?
答案 0 :(得分:1)
最快的变化是在开关中取出这些线:
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线程上执行Cursor查询,从而导致响应能力较差甚至应用程序无响应错误。或者,使用带有CursorLoader的LoaderManager。