我有一个自定义ArrayAdapter,它被设置为包含来自数据库的数据的列表视图:
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, database.getAll());
listview.setAdapter(adapter);
现在,我希望当用户删除listview应刷新的数据库项时。 到目前为止,我可以从数据库中成功删除该项目,但它仍保留在列表视图中。在ArrayAdapter类中,我将refresh()方法从一个新类调用到适配器的父类
public void refresh(){
ParentClass class_par = new ParentClass();
class_par.refreshfromParent();
}
在ParentClass中我有一个新方法: refreshfromParent()
public void refreshfromAlarm(){
DatabaseHandler database = new DatabaseHandler(myview.getContext());
listview.setAdapter(new CustomAdapter(myview.getContext(), -1, database.getAll())); // here I change listview adapter, and populate it with new database data, but I get NullPointerException
}
那么,我该如何刷新listview项目?请不要提及notifyDataSetChanged(),它不起作用。
答案 0 :(得分:0)
这里你犯了错误
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, database.getAll());
listview.setAdapter(adapter);
//so first you should make an arrayList and define it globally like
// ArrayList <yourType>list = new ArrayList<>();
//then initialize your adapter like this
list.addAll(databse.getAll());
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, list);
listview.setAdapter(adapter);
// now when you want to delete an item
// delete it from your list like list.remove(location)
// and also delete same item from your datebase
// after that just call this
notifyDataSetChanged();
答案 1 :(得分:0)
我意识到notifyDataSetChanged是一个很大的麻烦,所以我决定关闭并重新加载包含我的listview的片段。因此,结果看起来与DataSetChanged相同,并且用户没有差异。眼睛。我建议每个到达这个问题的人都这样做。