创建Contentprovider,

创建Contentprovider:

1. 创建一个provider----ExampleContentProvider

package com.hualu.contentprovider;

import java.util.HashMap;
import java.util.Map;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
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;

public class ExampleContentProvider extends ContentProvider {

	/*
     * Defines a handle to the database helper object. The MainDatabaseHelper class is defined
     * in a following snippet.
     */
    private MainDatabaseHelper mOpenHelper;

    // Defines the database name
    private static final String DBNAME = "mydb";
    
    
    private static final int MAINS = 1 ;
    private static final int MAIN_ID = 2 ;

    /**
     * A UriMatcher instance
     */
    private static final UriMatcher sUriMatcher;
    
    private static Map<String, String > columnMap = new HashMap<String, String>() ;
    static{
    	 // Create a new instance
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Main.AUTHORITY, "mains", MAINS) ;
        sUriMatcher.addURI(Main.AUTHORITY, "main", MAIN_ID) ;
        sUriMatcher.addURI(Main.AUTHORITY, "main/#", MAIN_ID) ;
        
        columnMap.put("id","_ID") ;
        columnMap.put("word","WORD") ;
    }

    public boolean onCreate() {

        /*
         * Creates a new helper object. This method always returns quickly.
         * Notice that the database itself isn't created or opened
         * until SQLiteOpenHelper.getWritableDatabase is called
         */
        mOpenHelper = new MainDatabaseHelper(
            getContext()      // the application context
        );

        return true;
    }
    
    

	
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
		case MAINS:{
			return Main.CONTENT_TYPE;
		}
		case MAIN_ID:{
			return Main.CONTENT_ITEM_TYPE;
		}
		}
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		if(sUriMatcher.match(uri) == MAIN_ID){
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
		ContentValues value  ;
		if(null != values){
			value = new ContentValues(values) ;
		}else{
			value = new ContentValues() ;
		}
		SQLiteDatabase db = mOpenHelper.getWritableDatabase() ;
		
		long rowId = db.insert(
				"main", 
				null, 
				values) ;
		 // If the insert succeeded, the row ID exists.
        if (rowId > 0) {
            // Creates a URI with the note ID pattern and the new row ID appended to it.
            Uri noteUri = ContentUris.withAppendedId(Uri.parse(Main.CONTENT_URI + "/main/"), rowId);

            // Notifies observers registered against this provider that the data changed.
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        // If the insert didn't succeed, then the rowID is <= 0. Throws an exception.
        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder sqb = new SQLiteQueryBuilder() ;
		sqb.setTables("main") ;
		switch (sUriMatcher.match(uri)) {
		case MAINS :
			sqb.setProjectionMap(columnMap) ;
			break ;
		case MAIN_ID :
			sqb.setProjectionMap(columnMap) ;
			sqb.appendWhere("_ID = " + 
					uri.getPathSegments().get(1)) ;
			break ;
		}
		String orderBy;
		// If no sort order is specified, uses the default
		if (TextUtils.isEmpty(sortOrder)) {
			orderBy = "_ID";
		} else {
			// otherwise, uses the incoming sort order
			orderBy = sortOrder;
		}
		
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor c = sqb.query(
							db, 
							projection, 
							selection, 
							selectionArgs, 
							null, 
							null, 
							orderBy) ;
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

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

	// A string that defines the SQL statement for creating a table
	private static final String SQL_CREATE_MAIN = "CREATE TABLE " +
	    "main " +                       // Table's name
	    "(" +                           // The columns in the table
	    " _ID INTEGER PRIMARY KEY, " +
	    " WORD TEXT" +
	    " FREQUENCY INTEGER " +
	    " LOCALE TEXT )";
	/**
	 * Helper class that actually creates and manages the provider's underlying data repository.
	 */
	protected static final class MainDatabaseHelper extends SQLiteOpenHelper {

	    /*
	     * Instantiates an open helper for the provider's SQLite data repository
	     * Do not do database creation and upgrade here.
	     */
	    MainDatabaseHelper(Context context) {
	        super(context, DBNAME, null, 1);
	    }

	    /*
	     * Creates the data repository. This is called when the provider attempts to open the
	     * repository and SQLite reports that it doesn't exist.
	     */
	    public void onCreate(SQLiteDatabase db) {

	        // Creates the main table
	        db.execSQL(SQL_CREATE_MAIN);
	    }

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			
		}
	}
	
}


2.定义权限

在manifest 中定义,permission

在<manifest>节点里面,定义permission

<permission android:name="com.hualu.provider.WRITE"></permission>
<permission android:name="com.hualu.provider.READ"></permission>


3.provider添加权限

在<provider> 节点里面添加

android:writePermission和android:readPermission

<provider android:authorities="@string/authority" android:name="ExampleContentProvider" 
            android:writePermission="com.hualu.provider.WRITE" 
            android:readPermission="com.hualu.provider.READ"></provider>


在另一个应用访问这个contentprovider

1.新建一个应用

2.在当前应用的manifest里面添加对之前定义的provider的权限的使用

<uses-permission android:name="com.hualu.provider.WRITE"/>
<uses-permission android:name="com.hualu.provider.READ"/>
3.在Activity里面通过ContentResolver调用provider
ContentValues values = new ContentValues() ;
		values.put("WORD", "abcd") ;
		
		Uri uri = this.getContentResolver().insert(
				Uri.parse("content://com.hualu.contentprovider/mains"),
				values) ;
		String id = uri.getPathSegments().get(1) ;
		
		
		Cursor cAll = this.getContentResolver().query(
				Uri.parse("content://com.hualu.contentprovider/mains"), 
				null, 
				null, 
				null,
				null);
		
		Cursor c = this.getContentResolver().query(
				Uri.parse("content://com.hualu.contentprovider/main/1"), 
				null, 
				null, 
				null,
				null);
		
		
		Toast.makeText(this, "insert success id = " + id + " ," +
				" \r\n All = " + cAll.getCount() + " , " +
				"\r\n one = " + c.getCount(),
				Toast.LENGTH_SHORT).show() ;



代码下载地址:

Contentprovider应用: http://download.csdn.net/detail/luhuajcdd/5140008

调用ContentProvider应用:http://download.csdn.net/detail/luhuajcdd/5140027


原文地址:https://www.cnblogs.com/java20130722/p/3207292.html