I have a RecyclerView
and a data retrieved from DB, but the insert animation cannot be shown due to
"Inconsistency detected. Invalid view holder adapter".
I am retrieving some items using an ArrayList
from a database as follow:
/* 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;
}
And then I pass the arrayList retrieved from DB to an activity. There is another arrayList named "itemList" for filtering the data retrieved from DB. Then pass the filered data from "itemList" to the RecyclerView for display. Code as follow:
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);
My RecyclerAdapter's notifyItemInserted function:
@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);
}
And iI notify that the problem is from the getItemCount from the ArrayList
, but I don't know how to fix it.