This question ask many times, but i cant understand properly, Here i am used Sqlite Database for simple chatting purpose and its all raw populate with recyclerview. What i had do ?
- create class MyDbHandler extends SQLiteOpenHelper
- create method which return List
In Activity class create an instance of adapter class and pass List in adapter.
public class MyDbHandler extends SQLiteOpenHelper {
public List<SqlMessages> sqlMessagesList() { String query = "SELECT * FROM " + TABLE_NAME; List<SqlMessages> messagesList=new LinkedList<>(); SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); SqlMessages sqlMessages; if (cursor.moveToFirst()) { do { sqlMessages.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID))); sqlMessages.setFromid(cursor.getString(cursor.getColumnIndex(COLUMN_FROM))); sqlMessages.setType(cursor.getString(cursor.getColumnIndex(COLUMN_TYPE))); sqlMessages.setMessage(cursor.getString(cursor.getColumnIndex(COLUMN_MESSAGE))); sqlMessages.setTimestamp(cursor.getLong(cursor.getColumnIndex(COLUMN_TIMESTAMP))); messagesList.add(sqlMessages); } while (cursor.moveToNext()); } return messagesList; }
}
Activity class
messagesAdapter=new MessagesAdapter(myDbHandler.sqlMessagesList());
when new message add
final SQLiteDatabase db= myDbHandler.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_MESSAGE, messageText);
values.put(COLUMN_FROM, MessageSenderId);
values.put(COLUMN_TYPE, TYPE_TEXT);
values.put(COLUMN_TIMESTAMP,tsLong);
long rowInserted = db.insert(TABLE_NAME,null, values);
if(rowInserted != -1)
{
Log.v("sqlitesave","ok");
messagesAdapter.notifyItemInserted(myDbHandler.sqlMessagesList().size()-1);
// to use of notifyItemInserted the app is crash(not every time but sometime) Logcat show below error
}
else
{
Log.v("sqlitesave","notok");
}
db.close();
LogCat
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{6cea9b9 position=15 id=-1, oldPos=14, pLpos:14 scrap [attachedScrap] tmpDetached no parent} android.support.v7.widget.RecyclerView{4aedc2 VFED..C.. ......I. 0,108-720,723 #7f080217 app:id/message_list_user}, adapter:".......".chat.MessagesAdapter@1cd2f63, layout:android.support.v7.widget.LinearLayoutManager@25f8760, context:"........".chat.MessageActivity@cd7aab8
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5715)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5898)
I tried
messagesAdapter.notifyDataSetChanged();
it works perfect and this types of question all developers answer is use notifyDataSetChanged
but for the further operarion i need to use of notifyItemInserted
So how to use notifyItemInserted in proper way withhandle this exception ?