内容提供者

一、继承ContentProvider

package com.shz.provider;

import com.shz.dao.SQLiteHelper;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class PersonProvider extends ContentProvider {

    private SQLiteHelper helper;
    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int INSERT = 1;
    private static final int DELETE = 2;
    private static final int UPDATE = 3;
    private static final int QUERY = 4;
    private static final int SINGLE = 5;

    static {
        matcher.addURI("db.personprovider", "insert", INSERT);
        matcher.addURI("db.personprovider", "delete", DELETE);
        matcher.addURI("db.personprovider", "update", UPDATE);
        matcher.addURI("db.personprovider", "query", QUERY);
        matcher.addURI("db.personprovider", "query/#", SINGLE);
    }

    @Override
    public boolean onCreate() {
        this.helper = new SQLiteHelper(getContext());
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        if (matcher.match(uri) == QUERY) {
            SQLiteDatabase db = this.helper.getReadableDatabase();
            Cursor cursor = db.query("person", projection, selection,
                    selectionArgs, null, null, sortOrder);
            return cursor;
        } else if (matcher.match(uri) == SINGLE) {
            long id = ContentUris.parseId(uri);
            SQLiteDatabase db = this.helper.getReadableDatabase();
            Cursor cursor = db.query("person", projection, "id=?",
                    new String[] { String.valueOf(id) }, null, null, sortOrder);
            return cursor;
        } else {
            throw new IllegalArgumentException("Uri参数不匹配");
        }
    }

    @Override
    public String getType(Uri uri) {
        if (matcher.match(uri) == QUERY) {
            return "vnd.android.cursor.dir/person";
        } else if (matcher.match(uri) == SINGLE) {
            return "vnd.android.cursor.item/person";
        }
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if (matcher.match(uri) == INSERT) {
            SQLiteDatabase db = this.helper.getWritableDatabase();
            db.insert("person", null, values);
        }

        // 通知观察者数据已发生改变
        getContext().getContentResolver().notifyChange(uri, null);
        return uri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int result = 0;
        if (matcher.match(uri) == DELETE) {
            SQLiteDatabase db = this.helper.getWritableDatabase();
            result = db.delete("person", selection, selectionArgs);
        }

        // 通知观察者数据已发生改变
        getContext().getContentResolver().notifyChange(uri, null);
        return result;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int result = 0;
        if (matcher.match(uri) == UPDATE) {
            SQLiteDatabase db = this.helper.getWritableDatabase();
            result = db.update("person", values, selection, selectionArgs);
        }

        // 通知观察者数据已发生改变
        getContext().getContentResolver().notifyChange(uri, null);
        return result;
    }

}

二、调用方法

package com.shz.testprovider;

import java.util.Random;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

    private static final String TAG = "testprovider";

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

    }

    public void queryAll(View view) {
        ContentResolver resolver = this.getContentResolver();
        Uri uri = Uri.parse("content://db.personprovider/query");
        Cursor c = resolver.query(uri, null, null, null, null);
        while (c.moveToNext()) {
            Log.i(TAG, "姓名:" + c.getString(c.getColumnIndex("name")));
        }

        c.close();
    }

    public void querySingle(View view) {
        ContentResolver resolver = this.getContentResolver();
        Uri uri = Uri.parse("content://db.personprovider/query/7");
        Cursor c = resolver.query(uri, null, null, null, null);
        while (c.moveToNext()) {
            Log.i(TAG, "姓名:" + c.getString(c.getColumnIndex("name")));
        }

        c.close();
    }

    public void insert(View view) {
        ContentResolver resolver = this.getContentResolver();
        Uri uri = Uri.parse("content://db.personprovider/insert");
        ContentValues values = new ContentValues();
        Random rand = new Random();
        values.put("name", "shz" + rand.nextInt(100));
        values.put("gender", "男");
        values.put("account", rand.nextInt(10000));
        resolver.insert(uri, values);
    }

    public void update(View view) {
        ContentResolver resolver = this.getContentResolver();
        Uri uri = Uri.parse("content://db.personprovider/update");
        ContentValues values = new ContentValues();
        Random rand = new Random();
        values.put("name", "dhf" + rand.nextInt(100));
        values.put("gender", "女");
        values.put("account", rand.nextInt(10000));
        resolver.update(uri, values, "id=1", new String[] { 5 + "" });
    }

    public void delete(View view) {
        ContentResolver resolver = this.getContentResolver();
        Uri uri = Uri.parse("content://db.personprovider/delete");
        Random rand = new Random();
        resolver.delete(uri, "id=?", new String[] { rand.nextInt(10) + "" });
    }

}

 三、AndroidManifest清单文件

<instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.shz.db" />

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="android.test.runner" />

        <activity
            android:name="com.shz.db.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <provider
            android:name="com.shz.provider.PersonProvider"
            android:authorities="db.personprovider"
            android:exported="true" >
        </provider>
    </application>

 

posted @ 2014-08-11 21:59  萌浩  阅读(156)  评论(0编辑  收藏  举报