Content Provider is primarily used to implement data sharing between different applications, and the content provider consists of two parts: using an existing content provider to read and manipulate the data in the corresponding program and to create your own content provider to provide external access to the data of our program.
1. Use an existing content provider to read and manipulate data in the corresponding program
If you want to access the data that is shared in the content provider, you must use Contentresolver. An instance of the class can be obtained through the Getcontentresolver () method in the Context. Contentresolver provides a series of methods for CRUD operations on data, where the Insert () method is used to add data, the update () method is used to update the data, and the Delete () method is used to delete the data, and the query () method is used to query the data. The difference is that Contentresolve receives not a table name parameter, but rather a URI (Uri Uri=uri.parse ("Content://com.example.app.provider/table1")).
(1) Get URI
Uri uri = uri.parse ("Content://com.example.app.provider/table1")
(2) Data manipulation
# query
cursor cursor = getcontentresolver (). Query ( URI, projection, selection, Selectionargs, SortOrder);
if NULL ) { while= cursor.getstring (Cursor.getcolumnindex ("Column1")); int column2 = Cursor.getint (Cursor.getcolumnindex ("Column2")); } Cursor.close (); }
# Insert Data
Contentvalues values = new Contentvalues (), Values.put ("Column1", "text"), Values.put ("Column2", 1); getcontentresolver (). Insert (URI, values);
2. Create your own content provider to provide external access to our program's data
Android first line code-9. Content Provider