我有一个RecyclerView
和一个从DB检索的数据,但是由于
“检测到不一致。视图持有人适配器无效”。
我正在使用ArrayList
从数据库中检索一些项目,如下所示:
/* Retrive data from database */
public List<AudioItem> getDataFromDB(){
List<AudioItem> audioList = new ArrayList<>();
String query = "select * from " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
AudioItem audio = new AudioItem();
audio.setId(Integer.parseInt(cursor.getString(0)));
audio.setName(cursor.getString(1));
audio.setFilePath(cursor.getString(2));
audio.setLength(Integer.parseInt(cursor.getString(3)));
audio.setTime(Long.parseLong(cursor.getString(4)));
audioList.add(audio);
}while (cursor.moveToNext());
cursor.close();
}
return audioList;
}
然后将从DB检索到的arrayList传递给一个活动。还有一个名为“arrayList”的itemList,用于过滤从DB检索的数据。然后将文件数据从"itemList“传递到RecyclerView以供显示。守则如下:
db = new DatabaseHelper(this);
dbList = new ArrayList<>();
dbList = db.getDataFromDB();
itemList = new ArrayList<>();
for (int i=0; i<dbList.size(); i++) {
if (dbList.get(i).getName().contains(titleName))
itemList.add(dbList.get(i));
}
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
//newest to oldest order (database stores from oldest to newest)
llm.setReverseLayout(true);
llm.setStackFromEnd(true);
mRecyclerView.setLayoutManager(llm);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new RecyclerAdapter(this, llm, itemList);
mRecyclerView.setAdapter(adapter);
我的回收适配器的notifyItemInserted函数:
@Override
public int getItemCount() {
return itemList.size();
}
@Override
public void onNewDatabaseEntryAdded() {
//item added to top of the list
Log.e("Count: ", Integer.toString(getItemCount()));
notifyItemInserted(getItemCount() - 1);
llm.scrollToPosition(getItemCount() - 1);
}
iI通知说问题来自ArrayList
的getItemCount,但我不知道如何解决它。
发布于 2016-05-29 04:49:24
类似于https://stackoverflow.com/a/32535796/3546306。只需尝试替换代码的下一行:
notifyItemInserted(getItemCount() - 1);
通过这个:notifyDataSetChanged(getItemCount());
https://stackoverflow.com/questions/37451796
复制相似问题