How to (properly) transition from startManagingCur

2019-02-05 21:11发布

问题:

I updated my android SDK to the latest version, and now it says that startManagingCursor() is deprecated. I need help to update my code to use the new CursorLoader.

private void fillData() {
    Cursor notesCursor = mDbHelper.fetchAllNotes();
    startManagingCursor(notesCursor);
    NoteAdapter notes = new NoteAdapter(this,  R.layout.notes_row, notesCursor);
    setListAdapter(notes);
}

So, startManagingCursor() is old, what would the new code look like, if it was translated?

回答1:

First, startManagingCursor() still works. It is not ideal, in that it performs database I/O on the main application thread. In Android, "deprecated" generally means "we have something else that we think is better that we suggest you use". So, when it makes sense in the development cycle of your app, you should consider migrating.

Second, as Selvin noted, the SDK only provides a Loader implementation for a ContentProvider. I have a project that offers a Loader for SQLite directly.

Third, there really is no straight-up "translation" for your code. The Loader framework is asynchronous and event-driven, whereas your code is not.

Generally speaking, your Loader would be responsible for fetching the notes, and you would populate your ListView in onLoadFinished(), when you are delivered the Cursor from the Loader.