2、DataBaseConfiguation 为程序所用到的配置信息 注:TableConfiguation内部类实现BaseColumns,即声明了_ID 和 _COUNT
3、MyContentProvider 自定义ContentProvider,继承与ContentProvider
其中 uriMatcher 为Uri的匹配器,在静态块中初始化URI。 columnMap为表结构的映射mapping
在getType方法中要根据访问的Uri确定访问资源的类型,以字符串形式返回。
格式为:"vnd.android.cursor.dir/vnd.catking.userList"、"vnd.android.cursor.item/vnd.catking.userItem";
注释掉,对程序运行无影响。
注意:
static{
//初始化URI
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(DataBaseConfiguation.AUTHORITY, "user", USER_LIST_CODE);
uriMatcher.addURI(DataBaseConfiguation.AUTHORITY, "user/#", USER_RECORD_CODE);
红色字体中,的格式为xxx/xx,并不是/xxx/xx,其中*号匹配所有字符,#匹配所有数字
//表结构的映射
columnMap.put(DataBaseConfiguation.TableConfiguation._ID, DataBaseConfiguation.TableConfiguation._ID);
columnMap.put(DataBaseConfiguation.TableConfiguation.USER_NAME, DataBaseConfiguation.TableConfiguation.USER_NAME);
}
最后在AndroidManifest.xml里配上
<provider android:authorities="com.catking.contentprovider.MyContentProvider" android:name="com.catking.contentprovider.MyContentProvider" />
ContentProviderTestActivity:
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.catking.cfg.DataBaseConfiguation;
public class ContentProviderTestActivity extends Activity {
private Button insertBtn;
private Button queryBtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
insertBtn = (Button) findViewById(R.id.insert);
queryBtn = (Button) findViewById(R.id.query);
insertBtn.setOnClickListener(new InsertOnClickListener());
queryBtn.setOnClickListener(new QueryOnClickListener());
}
class InsertOnClickListener implements OnClickListener{
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(DataBaseConfiguation.TableConfiguation.USER_NAME, "张三");
Uri uri = getContentResolver().insert(DataBaseConfiguation.TableConfiguation.CONTENT_URI, values);
System.out.println("uri------------------->" + uri);
}
}
class QueryOnClickListener implements OnClickListener{
@Override
public void onClick(View v) {
Cursor cursor = getContentResolver().query(DataBaseConfiguation.TableConfiguation.CONTENT_URI,
null, null, null, null);
while (cursor.moveToNext()) {
System.out.println(cursor.getString(cursor.getColumnIndex(DataBaseConfiguation.TableConfiguation.USER_NAME)));
}
}
}
}
DataBaseConfiguation:
import android.net.Uri;
import android.provider.BaseColumns;
public class DataBaseConfiguation {
public static final String AUTHORITY = "com.catking.contentprovider.MyContentProvider";
public static final String DATABASE_NAME = "cp_db";
public static final int DATABASE_VERSION = 1;
public static class TableConfiguation implements BaseColumns{
public static final String TABLE_NAME = "user";
public static final Uri CONTENT_URI = Uri.parse("content://" + DataBaseConfiguation.AUTHORITY + "/" + TABLE_NAME);
public static final String CONTENT_TYPE_DIR = "vnd.android.cursor.dir/vnd.catking.userList";
public static final String CONTENT_TYPE_RECORD = "vnd.android.cursor.item/vnd.catking.userItem";
public static final String USER_NAME = "name";
public static final String DEFAULT_SORT_ORDER = "_id desc";
}
}
MyContentProvider:
private static final UriMatcher uriMatcher;
private static final int USER_LIST_CODE = 1;
private static final int USER_RECORD_CODE = 2;
private SQLiteOpenHelper dbh;
private static Map<String, String> columnMap = new HashMap<String, String>();
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(DataBaseConfiguation.AUTHORITY, "user", USER_LIST_CODE);
uriMatcher.addURI(DataBaseConfiguation.AUTHORITY, "user/#", USER_RECORD_CODE);
columnMap.put(DataBaseConfiguation.TableConfiguation._ID, DataBaseConfiguation.TableConfiguation._ID);
columnMap.put(DataBaseConfiguation.TableConfiguation.USER_NAME, DataBaseConfiguation.TableConfiguation.USER_NAME);
}
@Override
public boolean onCreate() {
dbh = new MySQLiteOpenHelper(getContext(), DataBaseConfiguation.DATABASE_NAME, null, DataBaseConfiguation.DATABASE_VERSION);
System.out.println("dbh ������");
return true;
}
@Override
public String getType(Uri uri) {
System.out.println("getTypeִ��");
switch (uriMatcher.match(uri)) {
case USER_LIST_CODE:
return DataBaseConfiguation.TableConfiguation.CONTENT_TYPE_DIR;
case USER_RECORD_CODE:
return DataBaseConfiguation.TableConfiguation.CONTENT_TYPE_RECORD;
default:
throw new RuntimeException("unknown uri " + uri.toString());
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
System.out.println("insert ִ��");
SQLiteDatabase db = dbh.getWritableDatabase();
long rowId = db.insert(DataBaseConfiguation.TableConfiguation.TABLE_NAME, null, values);
if (rowId > 0) {
Uri insertedUri = ContentUris.withAppendedId(DataBaseConfiguation.TableConfiguation.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(insertedUri, null);
return insertedUri;
}
throw new SQLException("fail to insert row into " + uri.toString());
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
System.out.println(DataBaseConfiguation.TableConfiguation.CONTENT_URI);
SQLiteDatabase db = dbh.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(DataBaseConfiguation.TableConfiguation.TABLE_NAME);
qb.setProjectionMap(columnMap);
switch (uriMatcher.match(uri)) {
case USER_LIST_CODE:
break;
case USER_RECORD_CODE:
System.out.println("��ʼ��ѯuri.getPathSegments()����");
for (String s : uri.getPathSegments()) {
System.out.println(s);
}
System.out.println("�����ѯuri.getPathSegments()����");
qb.appendWhere(DataBaseConfiguation.TableConfiguation.USER_NAME + "=" + uri.getPathSegments().get(1));
break;
default:
throw new RuntimeException("unknown uri " + uri.toString());
}
Cursor c = db.query(DataBaseConfiguation.TableConfiguation.TABLE_NAME, projection, selection, selectionArgs, null, null,
DataBaseConfiguation.TableConfiguation.DEFAULT_SORT_ORDER);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
MySQLiteOpenHelper:
public MySQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
System.out.println("createDB excuted");
String createSQL = "create table " + DataBaseConfiguation.TableConfiguation.TABLE_NAME + "("
+ DataBaseConfiguation.TableConfiguation._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ DataBaseConfiguation.TableConfiguation.USER_NAME + " VARCHAR(20)" + ")";
System.out.println(createSQL);
db.execSQL(createSQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("onUpgrade excuted");
}
AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.catking.activity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".ContentProviderTestActivity"
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:authorities="com.catking.contentprovider.MyContentProvider" android:name="com.catking.contentprovider.MyContentProvider" />
</application>