我正在从android中的数据库创建一个arraylist,用于回收器视图的适配器:
RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.homeRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
ArrayList<StocksforHome> stockList = new ArrayList<>();
DbInteract interact = new DbInteract(getContext());
Cursor cursor = interact.readtable();
HomeFragmentAdapter homeFragmentAdapter = new HomeFragmentAdapter(stockList, getContext());
GetHomeData getHomeData = new GetHomeData(getContext(),homeFragmentAdapter);
int i=0;
stockList.clear();
while(cursor.moveToNext())
{
StocksforHome temp = new StocksforHome();
temp.stock = cursor.getString(cursor.getColumnIndex(eventDBcontract.ListofItem.columnsym));
stockList.add(temp);
}
homeFragmentAdapter.addall(stockList);
Log.d(tag,String.valueOf(stockList.size()) + " " + String.valueOf(cursor.getCount()));
recyclerView.setAdapter(homeFragmentAdapter);
数据库中只有一个数据,但arraylist的大小仍然是2.我检查了额外数据是否与第一个数据重复。 日志报告:
D/HomeFragment: 2 1
我制作了一个自定义适配器。它的addall方法是:
public void addall(ArrayList<StocksforHome> more)
{
stockArrayList.addAll(more);
notifyDataSetChanged();
}
知道为什么会这样,以及如何解决它?
答案 0 :(得分:1)
这是因为适配器中的stockList
和代码段中的stockList
是相同的引用,因此结果项会被添加两次。要修复此适配器,需要使用自己的List
实例。
首先添加:
stockList.add(temp);
第二次添加:
homeFragmentAdapter.addall(stockList);
像这样修复适配器:
HomeFragmentAdapter {
private final List<StocksforHome> stockList = new Arraylist<>();
public HomeFragmentAdapter(Context context) {
}
public void addall(List<StocksforHome> more) {
stockList.clear();
stockList.addAll(more);
notifyDataSetChanged();
}
}
答案 1 :(得分:0)
试试这个。
RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.homeRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
ArrayList<StocksforHome> stockList = new ArrayList<>();
DbInteract interact = new DbInteract(getContext());
Cursor cursor = interact.readtable();
HomeFragmentAdapter homeFragmentAdapter;
GetHomeData getHomeData = new GetHomeData(getContext(), homeFragmentAdapter);
int i = 0;
// clear and add data in your code
stockList.clear();
while (cursor.moveToNext()) {
StocksforHome temp = new StocksforHome();
temp.stock = cursor.getString(cursor.getColumnIndex(eventDBcontract.ListofItem.columnsym));
stockList.add(temp);
}
if (homeFragmentAdapter == null) {
homeFragmentAdapter = new HomeFragmentAdapter(stockList, getContext());
Log.d(tag, String.valueOf(stockList.size()) + " " + String.valueOf(cursor.getCount()));
recyclerView.setAdapter(homeFragmentAdapter);
} else {
// add all data
homeFragmentAdapter.addall(stockList);
}
首先,获取数据
其次,将其设置为适配器
homeFragmentAdapter = new HomeFragmentAdapter(stockList, getContext());
刷新代码中的数据
homeFragmentAdapter.addall(stockList);