Android:如何使用CursorAdapter?

use*_*146 16 android android-cursoradapter

我有一个数据库,一个ListView和一个CustomCursorAdapter扩展CursorAdapter.菜单按钮将项添加到数据库.我希望ListView更新并显示此更改.通常情况下,在我转到主屏幕并重新打开应用程序之前,它不会显示此新项目.

我最终通过调用cursor.requery()mCustomCursorAdapter.changeCursor(newCursor)每当我添加一个新项目来CursorAdapter使它工作,但是当我在构造函数中将autoRequery设置为false时,它的工作原理相同.当autoRequery设置为false时,为什么会正确更新?

我使用CursorAdapter得当吗?使用数据库更新列表的标准方法是什么?autoRequery有什么作用?

Ric*_*ler 37

自动更新Cursors 的惯用和imho正确方法Cursor#setNotificationUri是在创建它们之前以及在将它们传递给任何请求它们之前进行调用.然后ContentResolver#notifyChangeCursorUri命名空间中的任何内容发生变化时调用.

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

content://org.example/all_mail
content://org.example/labels
content://org.example/messages
Run Code Online (Sandbox Code Playgroud)

现在,假设我想要一个光标给我所有邮件,并在新邮件到达时更新:

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

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

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

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

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

而且,也许光标正在查看一个特定的消息,所以也通知他们:

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

getContentResolver()通话发生在数据被访问.所以,如果它在一个ServiceContentProvider那个你setNotificationUri和你的地方notifyChange.您不应该从访问数据的位置执行此操作,例如,Activity.

AlarmProvider是一个简单的ContentProvider使用此方法来更新Cursors.