Search code examples
androidsqlitelistviewcursor

Update ListView with cursor and SimpleCursorAdapter


My cursor is fetch data from sqlite.

msgsdbadapter = new MSGSDBAdapter(this);
msgsdbadapter.open();
cons_cursor = msgsdbadapter.fetchConversations();
startManagingCursor(cons_cursor);

After that I create a SimpleCursorAdapter and assign it to ListView. The ListView now can display some records well.

String[] from = new String[] { MSGSDBAdapter.KEY_FROM, MSGSDBAdapter.KEY_MSG, MSGSDBAdapter.KEY_DATE};
int[] to = new int[] { R.id.lblFrom, R.id.lblMsgExcerpt, R.id.lblDate };
cons_cursor_adapter = new SimpleCursorAdapter(context, R.layout.conversation_item, cons_cursor, from, to);
lvConversations.setAdapter(cons_cursor_adapter);

Next, I insert new row into table and notify dataset changed, but the ListView is not update

msgsdbadapter.createMsg(msg);
cons_cursor_adapter.notifyDataSetChanged();

And when I should close the db connection?


Solution

  • You need to either requery() the existing Cursor, or run the query again to get a fresh Cursor and swap the new Cursor into your CursorAdapter.