New SimpleCursorAdapter whenever data changes?
I'm just starting out with Android development and have been building a simple app that uses a ListActivity
, a SQLiteDatabase
, and a SimpleCursorAdapter
.
On the Android developer website there is an example project that demonstrates the usage of the SimpleCursorAdadpter
. Looking at the implementation, whenever the underlying database is modified as a result of some user action, the ListActivity
explicitly calls the following function to "refresh" the list:
开发者_运维百科private void fillData() {
// Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{NotesDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, mNotesCursor, from, to);
setListAdapter(notes);
}
It looks like a new SimpleCursorAdapter
is created every time and bound to the view with setListAdapter()
. Is this the best/cleanest implementation? The fact that this is on the Android website lends it a lot of credibility, however I looked at the CursorAdapter
documentation and saw there is a changeCursor()
method that seems to lend itself to a cleaner implementation than the one above, but I'm just not sure what that might look like.
Maybe I'm just fretting over nothing, but coming from the C/C++ world, and seeing this "new" object created each time you insert/delete a row from the database seems a bit heavy-handed.
Yes, you are right. You can see that a lot of times. For small lists that may not produce any problems when list is always created in onResume. But that's no good style. You can use cursor.changeCursor() or adapter.notifyDataSetChanged().
精彩评论