softcat2008 2009-07-09 23:31
浏览 297
已采纳

关于ListView和数据库配合的问题

请教一个问题,我们都知道ListView可以通过SimpleCursorAdapter和数据库进行关联。这里可以通过2种方式:
1) 通过Content Provider

例如:
----------------------------------------------------------------------------------
  Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
                Notes.DEFAULT_SORT_ORDER);

        // Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.noteslist_item, cursor,
                new String[] { Notes.TITLE }, new int[] { android.R.id.text1 });
        setListAdapter(adapter);
...............................................................

这样关联的好处,是假如数据库的内容发生变化,会自动的反映到关联的ListView上面

2)通过DBAdapter直接关联

其实这种方式就是我直接通过SQLiteOpenHelper的查询语句(rawQuery)得到一个Cursor,然后下面的步骤就和第一种方式一样了

例如:
  Cursor cursor = md.queryMessages(null, null, null, -1, -1, null);
        this.startManagingCursor(cursor);
        // An array of column names that will be added to the Map associated with each item.
        String[] from = new String[]{"_id","title","date"};
        //The views that should display column in the "from" parameter. These should all be TextViews.
       
        int[] to = {R.id.text1,R.id.text2,R.id.text3};
        // Now create an array adapter
        SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this, R.layout.messagelist, cursor, from, to);
        ViewBinder binder = new MessageViewBinder();
        listAdapter.setViewBinder(binder);
        listView.setAdapter(listAdapter);
.............................................................................................

我的问题是,假如用第2种方式,能否也实现ListView自动响应数据库内容变化,就像第一种方式的效果。
我试了一下,好像不行,大侠们能不能给点意见。

先谢了!
问题补充:
这个问题大概,我明白了。在ListView里只能直接通过Cursor的
cursor.deactivate();
cursor.requery();
来解决!

  • 写回答

1条回答 默认 最新

  • iteye_7779 2009-07-09 23:31
    关注

    如果你是继承ListActivity的话, 然后用:
    notifyDataSetChanged(); 来更新list的data.

    但如果是单单Activity, 我还没找到相应方法, 只好重新设置list的adapter

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型