在我的代码,现在,为了正确刷新列表视图我不得不重新获取我的数据库信息并重新创建SimpleCursorAdapter
。使用notifyDataSetChanged上SimpleCursorAdapter不起作用
例如,我在列表视图中有一个按钮。当单击此按钮时,它会从列表视图项目的数据库中删除条目。所以我想要发生的是从列表视图中删除项目,而不必重新创建适配器。
我试图改变我从全球到SimpleCursorAdapter
BaseAdapater
(因为它扩展SimpleCursorAdapater
,并允许使用的notifyDataSetChanged()
功能),但它仍然无法正常工作。
这是我现在使用的代码(没有工作):
代码global
声明和onCreate()
:
private RoutinesDataSource datasource;
private SimpleCursorAdapter dataAdapter;
private boolean isEditing = false;
private Toast toast_deleted;
private String[] columns = new String[] { MySQLiteHelper.COLUMN_NAME };
private int[] to;
@SuppressLint("ShowToast")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_routines);
toast_deleted = Toast.makeText(this, "", Toast.LENGTH_SHORT);
datasource = new RoutinesDataSource(this);
datasource.open();
Cursor cursor = datasource.fetchAllRoutines();
to = new int[] { R.id.listitem_routine_name };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_routine, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
代码为ListView物品内部的删除按钮:
public void onClick(View view) {
ListView l = getListView();
int position = l.getPositionForView(view);
Cursor cursor = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
cursor.moveToPosition(position);
long id = cursor.getLong(cursor.getColumnIndex(MySQLiteHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NAME));
switch (view.getId()) {
case R.id.button_routine_delete:
toast_deleted.setText(getString(R.string.toast_routine_deleted));
toast_deleted.show();
datasource.deleteRoutine(id);
onResume();
break;
}
}
。注意到我使用onResume()
的。
我知道datasource.deleteRoutine(id)
作品,因为当我关闭活动,并重新打开它的列表项消失了。
代码的onResume(),它正确地显示了清单,删除列表视图项:
@Override
protected void onResume() {
datasource.open();
Cursor cursor = datasource.fetchAllRoutines();
if (isEditing) {
to = new int[] { R.id.listitem_routine_edit_name };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_routine_edit, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
else {
to = new int[] { R.id.listitem_routine_name };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_routine, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
super.onResume();
}
我只是觉得它不好的做法,我只是想要一个列表项中移除,每次已删除重新创建适配器来自数据库。就像我说的我已经尝试了一个BaseAdapater的notifyDataSetChanged,它根本不起作用。
还注意到isEditing
布尔的。如果在显示删除按钮的操作栏中单击编辑按钮,则该设置为true。这很有用,因为我也有一个编辑按钮,当点击时它会启动一个活动,所以当它们在完成编辑后回来时仍然显示用户的按钮。
所以不管怎么说,能有人指出我如何刷新列表,而无需重新创建适配器 - 或者是我做了什么的最好方法是什么?
我在这里回答了一个类似的查询 - http://stackoverflow.com/questions/13953171/update-the-listview-after-inserting-a-new-record-with-simplecursoradapter-requ/13953470#13953470 – mango
谢谢。我会尝试一下。 – scarhand
非常感谢芒果! – scarhand