当我从sqlite表中删除一行时,ListView总是在删除最后一个条目时进行更新。重新启动活动时,它会正确反映数据库内容。
这就是我从表中删除一行的方法(mDb是一个SQLiteOpenHelper对象):
mDb.delete(TABLE, COL_ID + "=" + id, null);
mContext.getContentResolver().notifyChange(DB_URI, null);
这就是列表更新(简化)的方式。我已经确认调用onLoadFinished()。
public class MyActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {
…
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calllist);
String[] from = new String[] { … };
int[] to = new int[] { ... };
notes = new SimpleCursorAdapter(this, R.layout.item, null, from, to, 0){
}
public final static class MyCursorLoader extends SimpleCursorLoader {
final Loader.ForceLoadContentObserver observer = new ForceLoadContentObserver();
@Override
public Cursor loadInBackground() {
Cursor c = mDb.rawQuery(SELECT_ALL, null);
c.registerContentObserver(this.observer);
c.setNotificationUri(getContext().getContentResolver(), DB_URI);
return c;
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (loader.getId() == LOADER_ID) {
notes.changeCursor(cursor);
notes.notifyDataSetChanged();
}
}
}
当我用一秒钟或更长时间延迟notifyChange(DB_URI,null)调用时,我似乎工作。这有必要吗?还有其他方法可以解决这个问题吗?