Data sharing using Content Provider

Keywords: Android

The Content Provider is used to share data between different applications. The application uses a ContentResolver object to manipulate the specified data.

1 Content Provider overview

The Content Provider implements a set of general methods to provide data addition, deletion, modification and query functions.
The application obtains the ContentResolver object by calling the getContentResolver() method of the Activity or other component class. For example:

ContentResolver resolver = getContentResolver();

Generally, ContentProvider has only one instance, which can communicate with multiple ContentResolver class objects of different applications (different processes).

When using Content Provider, the following two concepts are usually used:

(1) Data model

Use simple tables based on the database model to record data. For example:

_ID

NAME

NUMBER

001

xxx

187xxxxxxxx

002

yyy

156yyyyyyy

003

zzz

131zzzzzzz

The query returns a Cursor object that can traverse each row and column to read the value of each field.

(2)URI

Each Content Provider provides a URI to uniquely identify its dataset.
Each ContentResolver method uses a URI as its first parameter, which identifies which provider and which table the ContentResolver should use.
The following is the composition of the Content URI:

content://com.android.contacts/contacts/001

[1]content:
Standard prefix, indicating that the data is managed by the Content Provider
[2]com.android.contacts:
The permission part of the URI is different for different applications.
[3]contacts/001:
Used to specify the data to be operated. 001 represents the ID of the specific record requested.

2. Create a Content Provider

To create a Content Provider:
(1) Inherit the ContentProvider class to provide data access.
(2) Declare the Content Provider in the application's AndroidManifest file.

(1) Inherit ContentProvider class

It means to implement six abstract methods of ContentProvider class:

method

explain

onCreate()

Used to initialize the provider

query()

Returns data to the caller

insert()

Insert new data

update()

Update data

delete()

Delete data

getType()

Return data MIME type

Since these ContentProvider methods can be called by ContentResolver objects of different threads or processes, they must be implemented in a thread safe manner.

(2) Declare Content Provider

That is, define the < provider > element in AndroidManifest.xml:

<provider
    android:name = "com.hyh.TestProvider"
    android.authorities = "com.hyh.testprovider"
    .../>
</provider>

The value of the name attribute is the name of a subclass of the ContentProvider class.
The authorities attribute is the authority part of the content:URI defined by the provider.

3. Using the Content Provider

The Android system provides predefined content providers for common data types, most of which are located in the android.provider package. Common content providers are as follows:

name
explain
Browser
Browser information
CallLog
Call history information
Contacts
contact information
LiveFolders
A specific folder of content provided by the ContentProvider
MediaStore
Multimedia information (sound, video, picture)
Setting
System settings
SearchRecentSuggestions
Create simple query suggestions for your application
UserDictionary
In predictable text input, provide user-defined words for input methods

The code is as follows:
MainActivity.java

public class MainActivity extends AppCompatActivity {
    private final String TAG = "ContentProvider";
    // Want a name
    private String columns = ContactsContract.Contacts.DISPLAY_NAME;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.READ_CONTACTS}, 1);
        }


        setContentView(R.layout.activity_main);
        // Gets the TextView component in the layout file
        TextView tv = (TextView) findViewById(R.id.result);
        // Set data for TextView
        tv.setText(getQueryData());
        // Textview add scroll bar
        tv.setMovementMethod(ScrollingMovementMethod.getInstance());
    }


    // Create getQueryData() method to obtain address book information
    private CharSequence getQueryData() {
        // Used to save strings
        StringBuilder sb = new StringBuilder();
        // Get ContentResolver object
        ContentResolver resolver = getContentResolver();
        // Query record
        Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        // Gets the index value of the name record
        int displayNameIndex = cursor.getColumnIndex(columns);
        // Iteration all records
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            String displayName = cursor.getString(displayNameIndex);
            sb.append(displayName + "\n");
        }
        // Close Cursor
        cursor.close();
        Log.d(TAG, "2 sb:" + sb);
        return sb.toString();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/textSize"
        android:lineSpacingExtra="@dimen/lineSpacingExtra"
        android:paddingLeft="@dimen/paddingLeft"
        android:paddingTop="@dimen/paddingTop"
        android:scrollbars="vertical"
        android:singleLine="false"
        />


</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hyh.contentprovider">


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ContentProvider">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


    <uses-permission android:name="android.permission.READ_CONTACTS"/>


</manifest>

Posted by standalone on Sun, 21 Nov 2021 16:58:45 -0800