Create data insert

The following code is from the NoteEditor class in the NotePad application. Code that was not relevant to the discussion was removed in the listing: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

final Intent intent = getIntent();

// Do some setup based on the action being performed. final String action = intent.getAction(); if (Intent.ACTION_EDIT.equals(action)) {

} else if (Intent.ACTION_INSERT.equals(action)) {

// Requested to insert: set that state, and create a new entry // in the container.

mUri = getContentResolver().insert(intent.getData(), null);

// Creating the new note failed finish();

return;

// Do something with the new note here.

The NotePad application starts out in the NotesList Activity. NotesList has an "Add Note" menu entry, shown in Figure 8-1.

When the user presses the Add Note button, the NoteEditor Activity is started with the ACTION_INSERT Intent. NoteEditor's onCreate method examines the Intent to determine why it was started. When the Intent is ACTION_INSERT, a new note is created by calling the insert method of the content resolver:

mUri = getContentResolver().insert(intent.getData(), null);

Figure 8-1. NotesList Activity

In brief, this line's job is to create a new blank note and return its URI to the mUri variable. The value of the mUri variable is the URI of the note being edited.

So how does this sequence of calls work? First, note that NotesList's parent class is ListActivity. All Activity classes are descended from ContextWrapper. So, the first thing the line does is call ContextWrapper.getContentResolver to return a ContentResolver instance. The insert method of that ContentResolver is then immediately called with two parameters:

URI of the content provider in which to insert the row

Our argument, intent.getData, resolves to the URI of the Intent that got us here in the first place, content://com.google.provider.NotePad/notes. Data to insert

Here, by passing null, we're inserting a record with no data. The data is added later with a call to the update method when the user types something in.

ContentResolver's job is to manipulate objects that URIs point to. Almost all of its methods are verbs that take a URI as their first argument. ContentResolver's methods include all of the CRUD methods, stream methods for file I/O, and others.

0 0

Post a comment