Книга: Beginning Android
Give and Take
Give and Take
Of course, content providers would be astonishingly weak if you couldn’t add or remove data from them, only update what is there. Fortunately, content providers offer these abilities as well.
To insert data into a content provider, you have two options available on the ContentProvider
interface (available through getContentProvider()
to your activity):
• Use insert()
with a collection Uri
and a ContentValues
structure describing the initial set of data to put in the row
• Use bulkInsert()
with a collection Uri
and an array of ContentValues
structures to populate several rows at once
The insert()
method returns a Uri
for you to use for future operations on that new object. The bulkInsert()
method returns the number of created rows; you would need to do a query to get back at the data you just inserted.
For example, here is a snippet of code from ConstantsBrowser
to insert a new constant into the content provider, given a DialogWrapper
that can provide access to the title and value of the constant:
private void processAdd(DialogWrapper wrapper) {
ContentValues values = new ContentValues(2);
values.put(Provider.Constants.TITLE, wrapper.getTitle());
values.put(Provider.Constants.VALUE, wrapper.getValue());
getContentResolver().insert(Provider.Constants.CONTENT_URI,
values);
constantsCursor.requery();
}
Since we already have an outstanding Cursor
for the content provider’s contents, we call requery()
on that to update the Cursor
’s contents. This, in turn, will update any SimpleCursorAdapter
you may have wrapping the Cursor
— and that will update any selection widgets (e.g., ListView
) you have using the adapter.
To delete one or more rows from the content provider, use the delete()
method on ContentResolver
. This works akin to a SQL DELETE
statement and takes three parameters:
1. A Uri
representing the collection (or instance) you wish to update
2. A constraint statement, functioning like a SQL WHERE
clause, to determine which rows should be updated
3. An optional set of parameters to bind into the constraint clause, replacing any ?s that appear there
- Galleries, Give or Take the Art
- Разработка приложений баз данных InterBase на Borland Delphi
- Open Source Insight and Discussion
- Introduction to Microprocessors and Microcontrollers
- Chapter 6. Traversing of tables and chains
- Chapter 8. Saving and restoring large rule-sets
- Chapter 11. Iptables targets and jumps
- Chapter 5 Installing and Configuring VirtualCenter 2.0
- Chapter 16. Commercial products based on Linux, iptables and netfilter
- Appendix A. Detailed explanations of special commands
- Appendix B. Common problems and questions
- Appendix E. Other resources and links