【问题标题】:Update ListView with cursor and SimpleCursorAdapter使用光标和 SimpleCursorAdapter 更新 ListView
【发布时间】:2011-12-14 18:01:56
【问题描述】:

我的光标正在从 sqlite 获取数据。

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

之后,我创建了一个 SimpleCursorAdapter 并将其分配给 ListView。 ListView 现在可以很好地显示一些记录了。

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);

接下来,我在表中插入新行并通知数据集已更改,但 ListView 未更新

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

我什么时候应该关闭数据库连接?

【问题讨论】:

  • onDestroy之前不需要关闭
  • 我认为您需要更新已传递给适配器的游标。
  • 如何更新游标?我可以创建新光标并将其再次分配给适配器。但是这样好像不好?

标签: android sqlite listview cursor


【解决方案1】:

您需要requery() 现有的Cursor,或者再次运行查询以获得新的Cursor 并将新的Cursor 换成您的CursorAdapter

【讨论】:

  • 重新查询已取消。有没有解决这个问题的新方法?
  • @complez:再次运行查询以获得新的Cursor,并使用changeCursor() 将新的Cursor 换成CursorAdapter
  • 这个更新的解决方案工作得很好,但我想知道为什么 adapter.notifyDataSetChanged() 不能自己做这个?
【解决方案2】:

如果您使用 ListFragment,最好的解决方案是将其放入此示例中:

 public SimpleCursorAdapter myNote;
    public class NOteLIST_MAIN extends ListFragment {

    @SuppressWarnings("deprecation")
    @Override
    public void onResume() {
        super.onResume();
        myNote.getCursor().requery();//Don't forget to put these on onResume }

    private void DataLoader(){private void DataFiller(){
          myNote = new SimpleCursorAdapter(getActivity(), R.layout.notes_row_line, notesCursor, from, to,0);
          setListAdapter(myNote);}  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    相关资源
    最近更新 更多