Content providers are one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only required if you need to share data between multiple applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. If you don’t need to share data amongst multiple applications you can use a database directly via SQLiteDatabase.
When a request is made via a ContentResolver the system inspects the authority of the given URI and passes the request to the content provider registered with the authority. The content provider can interpret the rest of the URI however it wants. The UriMatcher class is helpful for parsing URIs.
ContentProvider + URI
RFC-3986
URI determines resource – local file, webpage, content in a app on a device.
ContentProvider URI starts from content://
Since Android 7.0 FileProvider
should be used for files access, URI starts from file://
Manifest
[code language=”xml”]
<provider android:authorities="com.testproject.example" android:name="com.testproject.example.StubContentProvider" android:directBootAware=["true" | "false"] android:enabled=["true" | "false"] android:exported=["true" | "false"] android:grantUriPermissions=["true" | "false"] android:icon="drawable resource" android:initOrder="integer" android:label="string resource" android:multiprocess=["true" | "false"] android:permission="string" android:process="string" android:readPermission="string" android:syncable=["true" | "false"] android:writePermission="string" >
. . .
</provider>
[/code]
ContentResolver
browse all ContentProviders
is OS and look for ContentProvider
that has authority
equals to authority
in URI
example
[code language=”java”]
// authority “com.testproject.example”
<provider android:authorities="com.testproject.example" android:name="com.testproject.example.StubContentProvider">
</provider>
// Uri -> authority “com.testproject.example”
Uri mUri = Uri.parse(“content://com.testproject.example/banks/detail”);
ContentResolver mContentResolver = mContext.getContentResolover();
Uri newItemUri = mContentResolver.insert(mUri, values);
Cursor cursor = mContentResolver.query(mUri, projection, selection, selectionArgs, sortOrder);
long rowCountAffected = mContentResolver.update(mUri, values, selection, selectionArgs);
long rowCountAffected = mContentResolver.delete(mUri, selection, selectionArgs);
[/code]
Links
https://developer.android.com/guide/topics/providers/content-provider-creating.html
https://developer.android.com/reference/android/content/ContentProvider.html
https://developer.android.com/guide/topics/manifest/provider-element.html
https://www.udacity.com/course/android-basics-data-storage–ud845