In the previous section, we introduced several methods for data persistence: preferences, files, and databases. Sqlitedatabase is recommended for storing complex data structures. However, sharing data becomes a challenge because the database is only available to the packages that create it.
In this section, we will introduce the unique Android Data Sharing Method: Using contentprovider. It also describes how to use the built-in contentprovider and create your own contentprovider to share data among multiple packages.
In Android, we recommend using contentprovider to share data. You can think of contentprovider as a data store. How it stores data is irrelevant to the program that uses it. It is important to obtain the data through the encoding interface.
Contentprovider is very similar to a database. You can perform addition, deletion, query, and modification operations.
However, unlike databases, they can store data in different ways. Data can be stored in databases, files, or even networks.
Android provides many useful contentproviders, as follows:
- Browser stores browser bookmarks and browsing history.
- Calllog stores missed calls and call records.
- Contacts stores contact details.
- Mediastore stores media files, such as audio, video, and images.
- Settings stores some configuration information about the device.
In addition to these built-in contentproviders, you can also create your own contentprovider.
To query a contentprovider, you must specify a query string in Uri format and a row. The URI query format is as follows:
<Standard_prefix >://< authority>/<data_path>/<ID>
The URI components are as follows:
- The standard prefix of contentprovider is content ://
- Authority specifies the contentprovider name. Contacts is the name of the contentprovider with built-in contacts. For third-party contentprovider, this authority may be a complete specified name, such as net. Manoel. provider or net. horsttnann. provider.
- Data_path specifies the type of request data. For example, if you are obtaining all contacts in contacts contentprovider, data_path should be people, that is, the URI will be like this: Content: // contacts/people
- Id specifies the request record. For example, if you are looking for contact 2 in contacts contentprovider, The URI will be like this: Content: // contacts/people/2
The following are examples of queries:
Content: // media/Internal/Images |
Back to the picture list on the device's internal storage |
Content: // media/external/Images |
Back to the image list on the external storage of the device |
Content: // call_log/CILS |
Return call history |
Content: // Browser/bookmarks |
Returns the bookmarks in the browser. |