Easy Tutorial
❮ Ios Dev Skills Es6 Number ❯

4.4.1 A Preliminary Exploration of ContentProvider

Category Android Basic Tutorial

Introduction to This Section:

>

This section introduces the last of the four major components in Android—ContentProvider (Content Provider). Some readers may wonder, "Aren't there five major components in Android, including Intent?" Yes, Intent is also very important, but it is just the link between these components! Let's talk about this ContentProvider. When would we use it? There are the following two scenarios:

It seems very powerful, but it is actually very simple to use. Let's learn about ContentProvider below. Official Documentation: ContentProvider In this section, we will explain the concept of ContentProvider, write a few commonly used examples of using system ContentProvider, and customize ContentProvider!


1. Explanation of the Concept of ContentProvider:


2. Using the ContentProvider Provided by the System

>

In fact, many times we use ContentProvider not to expose our own data, but more often to read information from other applications through ContentResolver. The most commonly used is to read system APP information, contacts, multimedia information, etc.! If you want to call these ContentProviders, you need to consult the relevant API documentation yourself! In addition, different versions may correspond to different URLs! Here's how to get the URL and the corresponding database table fields, taking the most commonly used contacts as an example, and others can be searched on Google~ raw_contact table, data table, mimetypes table!


1) Simple Reading of Inbox Information:

Core Code:

private void getMsgs(){
    Uri uri = Uri.parse("content://sms/");
    ContentResolver resolver = getContentResolver();
    //What columns of information are obtained
    Cursor cursor = resolver.query(uri, new String[]{"address","date","type","body"}, null, null, null);
    while(cursor.moveToNext())
    {
        String address = cursor.getString(0);
        String date = cursor.getString(1);
        String type = cursor.getString(2);
        String body = cursor.getString(3);
        System.out.println("Address:" + address);
        System.out.println("Time:" + date);
        System.out.println("Type:" + type);
        System.out.println("Content:" + body);
        System.out.println("======================");
    }
    cursor.close();
}

Don't forget to add the permission to read the inbox in AndroidManifest.xml:

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

Running Results:

Some running results are as follows:


2) Simply Insert a Message into the Inbox

Core Code:

private void insertMsg() {
    ContentResolver resolver = getContentResolver();
    Uri uri = Uri.parse("content://sms/");
    ContentValues conValues = new ContentValues();
    conValues.put("address", "123456789");
    conValues.put("type", 1);
    conValues.put("date", System.currentTimeMillis());
    conValues.put("body", "no zuo no die why you try!");
    resolver.insert(uri, conValues);
    Log.e("HeHe", "SMS insertion completed~");
}

Running Results:

Note:

The above code can implement the function of writing SMS below 4.4, but it cannot be written on 5.0. The reason is: Starting from 5.0, software other than the default SMS application cannot send SMS messages in the form of writing to the SMS database!


3) Simple Reading of Mobile Phone Contacts

Core Code:

private void getContacts(){
    //①Query the raw_contacts table to get the contact's ID
    ContentResolver resolver = getContentResolver();
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    //Query contact data
    cursor = resolver.query(uri, null, null, null, null);
    while(cursor.moveToNext())
    {
        //Get the contact name, mobile number

ContentProviderOperation op4 = ContentProviderOperation.newInsert(dataUri)
            .withValueBackReference("raw_contact_id", 0)
            .withValue("mimetype", "vnd.android.cursor.item/email_v2")
            .withValue("data1", "779878443@qq.com")
            .withValue("data2", "2")
            .build();
    operations.add(op4);
    //Add the above content to the phone contacts~
    resolver.applyBatch("com.android.contacts", operations);
    Toast.makeText(getApplicationContext(), "Added successfully", Toast.LENGTH_SHORT).show();
}

**Running result:**

**Don't forget permissions:**

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


---

## 3. Custom ContentProvider

>

We rarely define our own ContentProvider because we often do not want our application's data to be exposed to
other applications. Although this is the case, learning how to use ContentProvider is still necessary. Having one more way to transfer data, right?

Next, we will implement it step by step:

Before we start, we need to create a database creation class (the database content will be discussed later~):

**DBOpenHelper.java**

public class DBOpenHelper extends SQLiteOpenHelper {

final String CREATE_SQL = "CREATE TABLE test(_id INTEGER PRIMARY KEY AUTOINCREMENT,name)";

public DBOpenHelper(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, null, 1);
}


@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_SQL);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

}


**Step 1**: Custom ContentProvider class, implement onCreate(), getType(), and override the corresponding add, delete, update, and query methods according to the requirements:

**NameContentProvider.java**

public class NameContentProvider extends ContentProvider {

//Initialize some constants
 private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);        
 private DBOpenHelper dbOpenHelper;

//For easy direct use of UriMatcher, addURI here, and then call Matcher for matching below

 static{  
     matcher.addURI("com.jay.example.providers.myprovider", "test", 1);
 }  

@Override
public boolean onCreate() {
    dbOpenHelper = new DBOpenHelper(this.getContext(), "test.db", null, 1);
    return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {
    return null;
}

@Override
public String getType(Uri uri) {
    return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {

    switch(matcher.match(uri))
    {
    //Put the database opening inside to prove that URI matching is complete
    case 1:
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        long rowId = db.insert("test", null, values);
        if(rowId > 0)
        {
            //Append the ID to the existing Uri in front
            Uri nameUri = ContentUris.withAppendedId(uri, rowId);
            //Notify that the data has changed
            getContext().getContentResolver().notifyChange(nameUri, null);
            return nameUri;
        }
    }
    return null;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    return 0;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
        String[] selectionArgs) {
    return 0;
}

}


**Step 2**: Register the ContentProvider in AndroidManifest.xml:

<!--Attributes in order: fully qualified class name, URI for matching, whether to share data --> <provider android:name="com.jay.example.bean.NameContentProvider" android:authorities="com.jay.example.providers.myprovider" android:exported="true" />


Okay, the part of the ContentProvider is completed!

---

Next, create a new project, and let's implement the part of ContentResolver. We will insert a piece of data directly by clicking a button:

**MainActivity.java**

public class MainActivity extends Activity {

private Button btninsert;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btninsert = (Button) findViewById(R.id.btninsert);

    //Read data from contentprovider  
    final ContentResolver resolver = this.getContentResolver();


    btninsert.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v)

WeChat Follow

❮ Ios Dev Skills Es6 Number ❯