ContentProvider是所有应用程序之间数据存储和检索的一个桥梁,作用是使得各个应用程序之间实现数据共享。
1.首先创建包含contentprovider的Content_uri和一些字段数据的NotePad类,字段类可以继承自BaseColumns类,代码如下
package com.lordbaby.ContentProvider; import android.net.Uri; import android.provider.BaseColumns; public class NotePad { //ContentProvider的Uri public static final String AUTHORITY="com.google.provider.NotePad"; private NotePad(){} //一些基本常量字段 public static final class Notes implements BaseColumns{ private Notes(){} public static final Uri CONTENT_URI=Uri.parse("content://"+AUTHORITY+"/notes"); //新的MIME类型-多个 public static final String CONTENT_TYPE="vnd.android.cursor.dir/vnd.google.note"; //新的MIME类型-单个 public static final String CONTENT_ITEM_TYPE="vnd.android.cursor.item/vnd.google.note"; //默认的排序方式 public static final String DEFAULT_SORT_ORDER="modified DESC"; //字段 public static final String TITLE="title"; public static final String NOTE="note"; public static final String CREATEDDATE="created"; public static final String MODIFIEDDATE="modified"; } }
2.然后创建自己的contentprovider类NotePadProvider,这里只写了查询和添加,以及打开创建数据库,具体实现代码如下
package com.lordbaby.ContentProvider; import java.sql.SQLException; import java.util.HashMap; import java.util.ResourceBundle; import com.lordbaby.ContentProvider.NotePad.Notes; 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.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.net.Uri; import android.text.TextUtils; public class NotePadProvider extends ContentProvider { private static final String TAG="NotePadProvider"; //数据库名 public static final String DATABASE_NAME="note_pad.db"; //数据库版本 public static final int DATABASE_VERSION=2; //表名 public static final String NOTES_TABLE_NAME="notes"; public static HashMap<String,String> sNotesProjectionMap; public static final int NOTES=1; public static final int NOTE_ID=2; public 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"+");"; private DataBaseHelper mOpenHelper; //用于匹配uri public static final UriMatcher sUriMatcher; static { System.out.println("start UriMatcher"); //常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码 sUriMatcher=new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES); sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID); //columnMap 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{ public DataBaseHelper(Context context) { //在这并没有真正的创建或者打开数据库,而是在getWritableDatabase() or getReadableDatabase() //被调用时才创建或者打开 super(context,DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } //创建表 @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub System.out.println("DataBaseHelper--------->onCreate Table"); db.execSQL(CREATE_TABLE); } //更新数据库 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } } @Override public boolean onCreate() { // TODO Auto-generated method stub System.out.println("NotePadProvider-------->onCreate "); mOpenHelper=new DataBaseHelper(getContext()); return true; } //查询操作 @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // TODO Auto-generated method stub 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); //这里获取的是uri中path部分,去掉去掉"/",的部分存于List<String>中,get(1)就是第二个值 //content://com.google.provider.NotePad/notes/1 path部分即notes/1 qb.appendWhere(Notes._ID+"="+uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unkown URI"+uri); } String orderBy; if (TextUtils.isEmpty(sortOrder)) { orderBy=NotePad.Notes.DEFAULT_SORT_ORDER; } else { orderBy=sortOrder; } System.out.println("NotePadProvider------>query"); SQLiteDatabase db=mOpenHelper.getReadableDatabase(); Cursor c=qb.query(db, projection, selection, selectionArgs, null, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } //如果有自定义类型必须实现该方法 @Override public String getType(Uri uri) { // TODO Auto-generated method stub System.out.println("NotePadProvider-------->getType"); switch (sUriMatcher.match(uri)) { case NOTES: //返回新的MIME类型-多个 return Notes.CONTENT_TYPE; case NOTE_ID: //返回新的MIME类型-单个 return Notes.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unkown Uri:"+uri); } } //插入数据库 @Override public Uri insert(Uri uri, ContentValues initialValues) { // TODO Auto-generated method stub System.out.println("NotePadProvider---->insert"); if (sUriMatcher.match(uri)!=NOTES) { throw new IllegalArgumentException("Unkown 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 r=Resources.getSystem(); values.put(NotePad.Notes.TITLE, r.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); System.out.println("insert---------->"+noteUri.toString()); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } System.out.println("Failed to insert row into :"+uri); return uri; } @Override public int delete(Uri arg0, String arg1, String[] arg2) { // TODO Auto-generated method stub return 0; } @Override public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) { // TODO Auto-generated method stub return 0; } }
3.Androidmainfest.xml文件中必须声明
<provider android:name="NotePadProvider" android:authorities="com.google.provider.NotePad"></provider>