ContentProvider 是android 里面重要组件之一 ,关于自定义ContentProvider 代码 以提供一个学生类的数据表为例
package com.content.provider; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { // private static final String @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void query(View view){ Cursor cursor=getContentResolver().query(Student.CONTENT_URI, null, null, null,null); String data=""; if(cursor.moveToFirst()){ data+="id"+cursor.getInt(0)+"name"+cursor.getString(1); } while(cursor.moveToNext()){ data+="id"+cursor.getInt(0)+"name"+cursor.getString(1); } cursor.close(); setTitle("查询成功!"); ((TextView)findViewById(R.id.textView1)).setText(data); } public void insert(View view){ ContentValues values=new ContentValues(); values.put("NAME", "123444"); getContentResolver().insert(Student.CONTENT_URI, values); setTitle("插入成功!"); } public void update(View view){ ContentValues values=new ContentValues(); values.put("name", "456"); String where="id=?"; String[] selectionArgs=new String []{"1"}; getContentResolver().update(Student.CONTENT_URI, values, where, selectionArgs); setTitle("更新成功!"); } public void delete(View view){ String where="id=?"; String[] selectionArgs=new String []{"1"}; getContentResolver().delete(Student.CONTENT_URI, where, selectionArgs); setTitle("删除成功!"); } }
package com.content.provider; 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.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.net.Uri; public class StudentContentProvider extends ContentProvider { private SQLiteDatabase mDatabase; private StudentDataBaseHelper mHelper; private static final String DB_NAME = "student.db"; private static Context mContext; private static int DB_VERSION = 1; private static final UriMatcher M_URI_MATCHER; private SQLiteQueryBuilder mLiteQueryBuilder = new SQLiteQueryBuilder(); static { M_URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); M_URI_MATCHER.addURI(Student.AUTHORITY, Student.TB_NAME, Student.STUDENT); M_URI_MATCHER.addURI(Student.AUTHORITY, Student.TB_NAME + "/#", Student.STUDENT_ITEM); } @Override public int delete(Uri uri, String arg1, String[] arg2) { mDatabase=mHelper.getWritableDatabase(); int row=mDatabase.delete(Student.TB_NAME, arg1, arg2); mContext.getContentResolver().notifyChange(uri, null); return row; } @Override public String getType(Uri uri) { int math = M_URI_MATCHER.match(uri); switch (math) { case Student.STUDENT: return Student.STUDENT_TYPE; case Student.STUDENT_ITEM: return Student.STUDENT_ITEM_TYPE; } return null; } @Override public Uri insert(Uri uri, ContentValues values) { mDatabase = mHelper.getWritableDatabase(); String tableName = uri.getPathSegments().get(0); if (tableName == null) throw new IllegalArgumentException(); if (null != values) { long rowId = mDatabase.insert(Student.TB_NAME, null, values); if (0 < rowId) { Uri newUri = ContentUris.withAppendedId(uri, rowId); mContext.getContentResolver().notifyChange(uri, null); return newUri; } } return null; } @Override public boolean onCreate() { mHelper = new StudentDataBaseHelper(getContext()); mHelper.close(); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { mDatabase = mHelper.getReadableDatabase(); String tableName = uri.getPathSegments().get(0); if (tableName == null) throw new IllegalArgumentException(); Cursor c = mDatabase.query(Student.TB_NAME, new String[] {}, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(mContext.getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { mDatabase = mHelper.getWritableDatabase(); String tableName = uri.getPathSegments().get(0); if (tableName == null) throw new IllegalArgumentException(); mLiteQueryBuilder.setTables(Student.TB_NAME); mLiteQueryBuilder.appendWhere("_id=" + uri.getLastPathSegment()); int row=mDatabase.update(Student.TB_NAME, values, selection, selectionArgs); mContext.getContentResolver().notifyChange(uri, null); return row; } private static class StudentDataBaseHelper extends SQLiteOpenHelper { public StudentDataBaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); mContext = context; } public StudentDataBaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE STUDENT (" + "ID" + " INTEGER PRIMARY KEY AUTOINCREMENT," + "NAME " + "TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS STUDENT"); onCreate(db); } } @Override protected void finalize() throws Throwable { if(null!=mDatabase) mDatabase.close(); super.finalize(); } }
package com.content.provider; import android.net.Uri; import android.provider.BaseColumns; public class Student implements BaseColumns{ public static final String TB_NAME="Student";//表名 public static final String AUTHORITY="com.content.provider.studentcontentprovider";//数据提供者的路径 public static final Uri CONTENT_URI=Uri.parse("content://"+AUTHORITY+"/"+TB_NAME);//访问学生类的URI public static final String STUDENT_TYPE="vnd.android.cursor.dir/vnd.aspire.student";// 学生表的数据类型 public static final String STUDENT_ITEM_TYPE="vnd.android.cursor.item/vnd.aspire.student";//学生表里的一条数据的类型 public static final int STUDENT=1;//所有数据 类型常量 public static final int STUDENT_ITEM=2;//一条数据的类型常量 }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.content.provider" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="4" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <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> </activity> <provider android:name=".StudentContentProvider" android:authorities="com.content.provider.studentcontentprovider"></provider> </application> </manifest>