我即将完成我的第一个 Android 应用程序,但是当我从为我的应用程序提供 ListView 的 SQLite 数据库中删除项目时,我遇到了一个奇怪的错误。该项目被删除,如果我从 ListView 切换回来,它会更新,但在我这样做之前,列表不会更新。
我在这里发布了大部分相关类(class):https://gist.github.com/2025973 ,但这里是文件中从第 56 行开始的相关回调:
builder.setPositiveButton(R.string.button_delete,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
databaseConnector.deleteSimpleDie(arg3);
storedDiceAdapter.notifyDataSetChanged();
}
});
我在这里做错了什么?我敢肯定这很简单。我最初在 Async 中删除,但后来我根本无法调用 notifyDataSetChanged(),因为它必须从创建 Cursor 的线程发生。
更新
好吧,这很贫民窟(我认为......)但我终于让它工作了。有人想告诉我这是多么可怕的错误吗?基本上,我只是在回调中重新实例化整个 CursorAdapter。它解决了问题,但我怀疑它有一些我不知道的负面影响。
builder.setPositiveButton(R.string.button_delete,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
databaseConnector.deleteSimpleDie(arg3);
String[] from = new String[] { "name", "description" };
int[] to = new int[] { R.id.dice_name, R.id.dice_description };
storedDiceAdapter = new SimpleCursorAdapter(StoredDice.this,
R.layout.stored_dice_item, null, from, to);
setListAdapter(storedDiceAdapter);
}
});
最佳答案
如果您曾经将基础数据集设置为新的内容,则适配器持有的您的引用将会中断。例如,这会破坏适配器:
Globals.diceList = newDiceList;
当你想完全改变你的数据集时,试试像这样的东西,这样你就不用经常重新调整你的适配器了。
Globals.diceList.clear();
Globals.diceList.addAll(newDiceList);
尽管在您的情况下,您应该改用简单的“删除”选项。这将修改列表的内容,而不更改引用它的位置。 (我知道 Java 很奇怪。)
我写上去比较深入的看一下here .
关于java - 为什么当我调用 notifyDataSetChanged() 时我的 ListView 没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9677093/