Android RecyclerView仅在应用程序启动时更新
这里是Android的新手 我一直在学习如何在我的应用程序中实现SQLite,总之,我有一个Android RecyclerView仅在应用程序启动时更新,android,android-sqlite,android-recyclerview,Android,Android Sqlite,Android Recyclerview,这里是Android的新手 我一直在学习如何在我的应用程序中实现SQLite,总之,我有一个accountary类,可以访问SQLite数据库。该类从数据库中提取项目,并将其放入ArrayList中。此ArrayList用于我的recyclerView适配器 每当我在应用程序中添加一个新项目时,该项目的数据都存储在数据库中,accountary类的ArrayList将使用此信息更新 然后,适配器调用其notifyDataSetChanged()方法来更新视图。这就是问题所在;RecyclerVi
accountary
类,可以访问SQLite数据库。该类从数据库中提取项目,并将其放入ArrayList
中。此ArrayList
用于我的recyclerView适配器
每当我在应用程序中添加一个新项目时,该项目的数据都存储在数据库中,accountary
类的ArrayList
将使用此信息更新
然后,适配器调用其notifyDataSetChanged()
方法来更新视图。这就是问题所在;RecyclerView
确实显示所有项目,但仅在应用程序启动时显示,而不是在添加新项目时显示
我已经尽了我所能,它看起来像是应该工作的,但它没有,这让我发疯
这是密码
项目适配器类private class ItemAdapter extends RecyclerView.Adapter<ItemHolder> {
private List<Item> mItemList;
public ItemAdapter(List<Item> itemList) {
mItemList = itemList;
}
public ItemHolder onCreateViewHolder(ViewGroup parent, int ViewType) {
View view = getLayoutInflater().inflate(R.layout.list_item_item, parent, false);
return new ItemHolder(view);
}
public void onBindViewHolder(ItemHolder holder, int position) {
Item item = mItemList.get(position);
holder.bindItem(item);
}
public int getItemCount() {
return mItemList.size();
}
}
还有一个根本性的问题,甚至与
RecyclerView
无关。
首先让我们看看如何解决您的问题,然后解释问题所在
改变这个
private List<Item> mItemList;
现在解释一下为什么代码不起作用。问题是,当您将数据源(即mItemList
)分配给某个新值时,您正在更改对它的引用(这是java的基本特性)因此,您的RecyclerView对它一无所知,并且它自己的数据源(您在构造函数中只分配了一次)仍然保持不变,因此您的notifyDataSetChanged
调用不会执行任何操作
一般建议每当使用
RecyclerView
或ListView
时,请确保将数据源定义为final
这是因为您没有将该项添加到Adpeter的列表中。在适配器内创建一个方法,并从Accountant类调用此方法
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder> {
public void addItem(Item item) {
mItemList.add(item); ///Add the item to your arrayList and then notify
notifyItemInserted(mItemList.size());
}
public void addItem(Item item) { ///This method is from Accountant Class
mAccountant.addItem(item);
mAdapter.addItem(item); // Call the addItem() from Adapter class
mChangeButton.setText(mAccountant.getChange());
}
希望它能工作…如果您的数据模型是基于
Cursor
的使用适配器,它就像一个CursorAdapter
用于“普通”ListView
s@pskink所以它也适用于RecyclerViews?公共抽象类CursorRecyclerAdapter扩展了RecyclerView.Adapter
谢谢你的建议,不过,该应用程序仍仅在启动时更新。我是否应该更改notifyDataSetChanged()
方法?请阅读的第2点,注意使用游标加载程序有三个主要好处
private final List<Item> mItemList;
mItemList.clear();
mItemList.addAll(getListFromSQL());
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder> {
public void addItem(Item item) {
mItemList.add(item); ///Add the item to your arrayList and then notify
notifyItemInserted(mItemList.size());
}
public void addItem(Item item) { ///This method is from Accountant Class
mAccountant.addItem(item);
mAdapter.addItem(item); // Call the addItem() from Adapter class
mChangeButton.setText(mAccountant.getChange());