Introduction to contentprovider in Android [Android Evolution]

Source: Internet
Author: User

For applications, data storage is very important. In [Android evolution 13], sharedpreferences is stored in simple key-value format and stored in mobile phones in XML format. This is simple and convenient, A good data storage tool can only store simple data. It is inconvenient to store a large amount of data. In [Android evolution 14th], I wrote an example of an SQLite database storing data address book. SQLite is a type of relational database that stores large amounts of data for convenient operations. Data storage also includes file storage and network storage. I will write examples later. Now I want to talk about my understanding of contentproviders. The sharedpreferences, SQLite, and so on mentioned above are all for every application. That is to say, you can only use this project instead of a project, however, some mobile phone programs need data sharing and cannot be used only for one project. (For example, the text message and address book of Android mobile phones are data sharing, the source code writes their corresponding contentprovider to provide us with this interface, we can operate on it) at this time we need contentproviders, it is a bridge between data storage and retrieval among many applications, and its main function is to share data among various applications. The system provides several frequently used contentproviders, such as audio, video, image, and personal contact information. This is the general description of contentproviders.


The following steps describe contentsproviders:

1. Create contentsprovider:

First, define a public and static constant in the contentsproviders class: content_uri to represent this address. The address must be unique: public static final URI content_uri = Uri. parse ("content: //" + authority + "/Notes"); the name of the data column that you want to return to the client must be defined. If you are using the SQLite database, the data column is used in the same way as other databases you are familiar. However, you must define a column named _ id for it to indicate the uniqueness of each record.
Primary Key autoincrement "is automatically updated.

Note: If the data type you process is a relatively new type, you must define a new MIME type to provide contentprovider. GetType (URI) for return. The MIME type can be either specified for a single record or specified for multiple records.
In addition, do not forget to use the <provider> label in androidmenifest. XML to set the content provider.

    <provider android:name="NotePadProvider"
              android:authorities="com.cn.daming.proider.NotePad"/>         


2. contentresolver class. The application uses this class to use a specific contentprovider,
Contentresolver CRS = getcontentresolver (); obtain a contentresolver object. You can use this class to add, delete, modify, and query data. For details, refer to the sdk api help documentation.
3. Uri: Each contentprovider provides a public uri (encapsulated as a URI object). When data is shared, you need to use contentprovider to define the URI for the data, then other applications can pass in this URI through contentprovider to operate the data. Uri consists of three parts: "content: //", the data path, ID (optional), and the system URI:

Content: // contacts/MMS/3 (obtain the contact record with ID 3 in the text message table)

Content: // contacts/MMS/(This URI will return all SMS messages on the device)

For ease of understanding, a series of helper classes are provided under the Android. provider package, including query strings in the form of class variables. The above can be changed:

        Uri person = ContentUris.withAppendedId(Mms.CONTENT_URI,3);                 

Note: In the data sharing query statement: where... and... or, can be used at the same time, multiple and, and one or more or at the same time, or multiple or and one or more and at the same time, it is clear that the query efficiency is very low when both or and are used, and the query speed is a little slow. Especially when used with like, the efficiency will be slower. If you have any questions, you can leave a message for the Code. For more information, mark the source:Http://blog.csdn.net/wdaming1986/article/details/6820442

For example: contentproviderdemo:


First read: Read the values inserted into the database:

 

Code:

Class under the com.cn. daiming package

I. Code in the notepad. Java class:

package com.cn.damingimport android.net.Uri;import android.provider.BaseColumns;public class NotePad {public static final String AUTHORITY = "com.cn.daming.proider.NotePad";private NotePad(){}public static final class Notes implements BaseColumns{private Notes(){}public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/notes");//new mime manypublic static final String CONTENT_TYPE = "daming.android.cursor.dir/cn.daming.note";//new mime onepublic static final String CONTENT_ITEM_TYPE = "daming.android.cursor.item/cn.daming.note";public static final String DEFAULT_SORT_ORDER = "modified DESC";//columnpublic static final String TITLE = "title";public static final String NOTE = "note";public static final String CREATEDDATE = "created";public static final String MODIFIEDDATE = "modified";}}

Ii. Code in the notepadprovider. Java class:

package com.cn.daming;import java.util.HashMap;import android.content.ContentProvider;import android.content.ContentUris;import android.content.ContentValues;import android.content.Context;import android.content.UriMatcher;import android.content.res.Resources;import android.database.Cursor;import android.database.SQLException;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteQueryBuilder;import android.net.Uri;import android.text.TextUtils;import com.cn.daming.NotePad.Notes;public class NotePadProvider extends ContentProvider{private static final String TAG = "NotePadProvider";//database nameprivate static final String DATABASE_NAME = "notepad_db";private static final int DATABASE_VERSION = 2;//table nameprivate static final String NOTES_TABLE_NAME = "notes";private static HashMap<String, String> sNotesProjectionMap;private static final int NOTES = 1;private static final int NOTE_ID = 2;private static final UriMatcher sUriMatcher;private DatabaseHelper  mOpenHelper;    private static final String CREATE_TABLE = "CREATE TABLE "                                             + NOTES_TABLE_NAME                                             +" ("+Notes._ID                                            +" INTEGER PRIMARY KEY, "                                            +Notes.TITLE                                            +" TEXT,"                                            +Notes.NOTE                                            +" TEXT, "                                            +Notes.CREATEDDATE                                            +" INTEGER,"                                            +Notes.MODIFIEDDATE                                            +" INTEGER" + ");";    static    {    sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);    sUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES);    sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID);        sNotesProjectionMap = new HashMap<String, String>();    sNotesProjectionMap.put(Notes._ID, Notes._ID);    sNotesProjectionMap.put(Notes.TITLE, Notes.TITLE);    sNotesProjectionMap.put(Notes.NOTE, Notes.NOTE);    sNotesProjectionMap.put(Notes.CREATEDDATE, Notes.CREATEDDATE);    sNotesProjectionMap.put(Notes.MODIFIEDDATE, Notes.MODIFIEDDATE);    }        private static class DatabaseHelper extends SQLiteOpenHelper    {        //create Database    DatabaseHelper(Context context)    {    super(context, DATABASE_NAME, null, DATABASE_VERSION);    }    //create tables@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(CREATE_TABLE);}//update Database@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {db.execSQL("DROP TABLE IF EXISTS notes");onCreate(db);}    }        @Overridepublic boolean onCreate() {mOpenHelper = new DatabaseHelper(getContext());    return true;}        @Override    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,    String sortOrder) {        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();        switch(sUriMatcher.match(uri))        {        case NOTES:        qb.setTables(NOTES_TABLE_NAME);        qb.setProjectionMap(sNotesProjectionMap);        break;        case NOTE_ID:        qb.setTables(NOTES_TABLE_NAME);        qb.setProjectionMap(sNotesProjectionMap);        qb.appendWhere(Notes._ID + "="+        uri.getPathSegments().get(1));        break;        default:        throw new IllegalArgumentException("Unknown URI"+uri);        }        String orderBy;        if(TextUtils.isEmpty(sortOrder))        {        orderBy = NotePad.Notes.DEFAULT_SORT_ORDER;        }        else        {        orderBy = sortOrder;        }        SQLiteDatabase db = mOpenHelper.getReadableDatabase();        Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);        cursor.setNotificationUri(getContext().getContentResolver(), uri);        return cursor;    }        //if you difine the class,must get the mothod    @Override    public String getType(Uri uri) {        switch(sUriMatcher.match(uri))        {            case NOTES:             return Notes.CONTENT_TYPE;            case NOTE_ID:             return Notes.CONTENT_ITEM_TYPE;        default:         throw new IllegalArgumentException("Unknown URI "+uri);        }    }        @Override    public Uri insert(Uri uri, ContentValues initialValues) {    if(sUriMatcher.match(uri) != NOTES)    {    throw new IllegalArgumentException("Unknown URI "+uri);    }    ContentValues values;    if(initialValues != null)    {    values = new ContentValues(initialValues);    }    else    {    values = new ContentValues();    }    Long now = Long.valueOf(System.currentTimeMillis());    if(values.containsKey(NotePad.Notes.CREATEDDATE) == false)    {    values.put(NotePad.Notes.CREATEDDATE, now);    }    if(values.containsKey(NotePad.Notes.MODIFIEDDATE) == false)    {    values.put(NotePad.Notes.MODIFIEDDATE, now);    }    if(values.containsKey(NotePad.Notes.TITLE) == false)    {    Resources recource = Resources.getSystem();    values.put(NotePad.Notes.TITLE, recource.getString(android.R.string.untitled));    }    if(values.containsKey(NotePad.Notes.NOTE) == false)    {    values.put(NotePad.Notes.NOTE, "");    }    SQLiteDatabase db = mOpenHelper.getWritableDatabase();    long rowId = db.insert(NOTES_TABLE_NAME, Notes.NOTE, values);    if(rowId > 0)    {    Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, rowId);    getContext().getContentResolver().notifyChange(noteUri, null);    return noteUri;    }    throw new SQLException("Failed to insert row into "+uri);    }    @Overridepublic int delete(Uri uri, String where, String[] whereArgs) {SQLiteDatabase db = mOpenHelper.getWritableDatabase();int count;switch(sUriMatcher.match(uri)){case NOTES:count = db.delete(NOTES_TABLE_NAME, where, whereArgs);break;case NOTE_ID:String noteId = uri.getPathSegments().get(1);count = db.delete(NOTES_TABLE_NAME, Notes._ID +"=" + noteId + (!TextUtils.isEmpty(where) ? " " +" AND (" + where + ')' : ""), whereArgs);break;default:throw new IllegalArgumentException("Unknown URI "+uri);}getContext().getContentResolver().notifyChange(uri, null);return count;}@Overridepublic int update(Uri uri, ContentValues values, String where, String[] whereArgs) {SQLiteDatabase db = mOpenHelper.getWritableDatabase();int count;switch(sUriMatcher.match(uri)){case NOTES: count = db.update(NOTES_TABLE_NAME, values, where, whereArgs); break;case NOTE_ID: String noteId = uri.getPathSegments().get(1); count = db.update(NOTES_TABLE_NAME, values, Notes._ID + "=" + noteId + (!TextUtils.isEmpty(where)?"" + "AND(" + where + ')' : ""), whereArgs); break;default:throw new IllegalArgumentException("Unknown URI " + uri);}getContext().getContentResolver().notifyChange(uri, null);return count;}}

3. Code in mainactivity. Java:

package com.cn.daming;import android.app.Activity;import android.content.ContentValues;import android.database.Cursor;import android.graphics.Color;import android.net.Uri;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends Activity {private TextView show_text_view1;private TextView show_text_view2;@Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                //insert value         ContentValues values = new ContentValues();        values.put(NotePad.Notes.TITLE, "From Daming");        values.put(NotePad.Notes.NOTE, "This is Daming Make!");        getContentResolver().insert(NotePad.Notes.CONTENT_URI, values);        values.clear();        values.put(NotePad.Notes.TITLE, "Daming blog");        values.put(NotePad.Notes.NOTE, "http://blog.csdn.net/wdaming1986/article/details/6820442!");        getContentResolver().insert(NotePad.Notes.CONTENT_URI, values);                //show the display        showDisplayNote();    }        //show the display    private void showDisplayNote()    {    String columns[] = new String[]{    NotePad.Notes._ID,    NotePad.Notes.TITLE,    NotePad.Notes.NOTE,    NotePad.Notes.CREATEDDATE,    NotePad.Notes.MODIFIEDDATE    };    Uri myUri = NotePad.Notes.CONTENT_URI;    show_text_view1 = (TextView)findViewById(R.id.show_textview1);    show_text_view2 = (TextView)findViewById(R.id.show_textview2);    Cursor cursor = managedQuery(myUri, columns, null, null, null);    if(cursor.moveToFirst())    {    String title = null;    String note = null;    for(int i=0;i<cursor.getCount();i++)    {    if(cursor.moveToPosition(i))    {    title = cursor.getString(cursor.getColumnIndex(NotePad.Notes.TITLE));    note = cursor.getString(cursor.getColumnIndex(NotePad.Notes.NOTE));    if(i==0)    {    show_text_view2.setText("TITLE:"+title+"\n"+"NOTE:"+note);    show_text_view2.setTextColor(Color.GREEN);    }    if(i==1)    {    show_text_view1.setText("TITLE:"+title+"\n"+"NOTE:"+note);    show_text_view1.setTextColor(Color.BLUE);    }    }    }    }    }}

Code in the main. xml layout file under layout:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:gravity="center_vertical|center_horizontal"    android:layout_marginTop="10dip"    android:text="@string/hello"    android:textSize="8pt"    /><TextView    android:id="@+id/show_textview1"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:gravity="center_vertical|center_horizontal"    android:layout_marginTop="20dip"    android:textSize="10pt"/><TextView    android:id="@+id/show_textview2"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:gravity="center_vertical|center_horizontal"    android:layout_marginTop="20dip"    android:textSize="10pt"/></LinearLayout>

Code in manifest. xml: [Be sure to declare contentprovider]

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.cn.daming"      android:versionCode="1"      android:versionName="1.0">    <uses-sdk android:minSdkVersion="8" />    <application android:icon="@drawable/icon" android:label="@string/app_name">        <provider android:name="NotePadProvider"                  android:authorities="com.cn.daming.proider.NotePad"/>        <activity android:name=".MainActivity"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>            <intent-filter>                <data android:mimeType="daming.android.cursor.dir/cn.daming.note"/>            </intent-filter>            <intent-filter>                <data android:mimeType="daming.android.cursor.item/cn.daming.note"/>            </intent-filter>        </activity>    </application></manifest>

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.