2010-08-23 76 views
16

我有一个数据库,ListViewCustomCursorAdapter,延伸CursorAdapter。菜单按钮将一个项目添加到数据库。我希望ListView更新并显示此更改。通常它不显示这个新项目,直到我进入主屏幕并重新打开应用程序。Android:如何使用CursorAdapter?

我也终于得到它通过调用cursor.requery()mCustomCursorAdapter.changeCursor(newCursor)每当我增加了一个新的项目工作,但是当我在CursorAdapter构造函数中设置autoRequery为false,它的工作一样。为什么autoRequery设置为false时会正确更新?

我正在使用CursorAdapter吗?用数据库更新列表的标准方式是什么? autoRequery做什么?

+0

@randzero意味着你要更新,每当新的项目在数据库中添加的列表视图项目, 这样对吗 ? – 2010-08-23 06:24:05

回答

37

自动更新Cursor s的习惯用法和imho正确的方法是在创建它们时以及在将它们交给任何请求它们之前调用Cursor#setNotificationUri。然后在Cursor的Uri名称空间发生更改时调用ContentResolver#notifyChange

例如,假设您正在创建一个简单的邮件应用程序,并且您希望在新邮件到达时进行更新,并且还提供有关邮件的各种视图。我会定义一些基本的Uri。

content://org.example/all_mail 
content://org.example/labels 
content://org.example/messages 

现在,说我想获得这给了我所有的邮件光标和更新,当新邮件到达时:

Cursor c; 
//code to get data 
c.setNotificationUri(getContentResolver(), Uri.parse("content://org.example/all_mail"); 

现在有新邮件到达,所以我通知:

//Do stuff to store in database 
getContentResolver().notifyChange(Uri.parse("content://org.example/all_mail", null); 

我还应该通知所有Cursor s选择的标签此新消息符合

for(String label : message.getLabels() { 
    getContentResolver().notifyChange(Uri.parse("content://org.example/lables/" + label, null); 
} 

而且也,也许光标观看一个特定的消息,以便通知他们还有:

getContentResolver().notifyChange(Uri.parse("content://org.example/messages/" + message.getMessageId(), null); 

getContentResolver()通话发生在数据被访问。所以,如果它在ServiceContentProvider这是你setNotificationUrinotifyChange。您不应该从访问数据的位置这样做,例如Activity

AlarmProvider是一个简单的ContentProvider,它使用此方法更新Cursor s。

+1

这真的很有帮助。感谢分享。 – 2010-10-01 14:12:36

+0

这篇文章真的很棒!在我的搜索帮助我很多! :) – 2010-12-16 07:20:38

+0

纠正我,如果我错了光标#setNotificationUri'更新光标与最新的数据,只要他们是一个'getContentResolver()。notifyChanged'是在'ContentProvider'中调用。 – 2012-05-21 09:15:07

1

我创建下一个方法的ListView更新:在数据库中的一些变化后,每次

/** 
* Method of refreshing Cursor, Adapter and ListView after database 
* changing 
*/ 
public void refreshListView() { 
    databaseCursor = db.getReadableDatabase().query(
      CurrentTableName, 
      null, 
      null, 
      null, 
      null, 
      null, 
      "title"+SortingOrder); 
    databaseListAdapter = new DomainAdapter(this, 
      android.R.layout.simple_list_item_2, 
      databaseCursor, 
      new String[] {"title", "description"}, 
      new int[] { android.R.id.text1, android.R.id.text2 }); 
    databaseListAdapter.notifyDataSetChanged(); 
    DomainView.setAdapter(databaseListAdapter); 
} 

末称之为

相关问题