ContentPRovider示例

1,创建数据库

package com.contentprovider.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	private static final String DB_NAME = "test.db";
	private static final String TABLE_NAME = "person";
	private static final int VERSION_CODE = 999;

	public DBHelper(Context context) {
		super(context, DB_NAME, null, VERSION_CODE);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql = "CREATE TABLE "
				+ TABLE_NAME
				+ " (id Integer primary key autoincrement, name varchar(10),sex varchar(10),age Integer);";
		db.execSQL(sql);
		
		initDB(db);
	}

	private void initDB(SQLiteDatabase db) {
		
		ContentValues values = new ContentValues();
		for (int i = 1; i <= 10; i++) {
			values.put("name", "zhangsan" + i);
			if (i % 2 == 0) {
				values.put("sex", "male");
			} else {
				values.put("sex", "female");
			}
			values.put("age", i + 30);
			db.insert(TABLE_NAME, "id", values);
		}
	}

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

	}

}

2,封装PersonPrivider

package com.contentprovider.provider;

import com.contentprovider.db.DBHelper;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import android.view.View;

public class PersonProvider extends ContentProvider {

	private static final String TAG = "PersonProvider";
	private static final String AUTHORITY = "com.contentprovider.provider";
	private static final String TABLE_NAME = "person";

	private static UriMatcher mUriMatcher;
	private DBHelper mHelper = null;

	private static final int PERSON_ONE_RECORD = 1;
	private static final int PERSON_ALL_RECORDS = 2;
	private SQLiteDatabase mDb;

	static {
		mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		mUriMatcher.addURI(AUTHORITY, TABLE_NAME, PERSON_ALL_RECORDS);
		mUriMatcher.addURI(AUTHORITY, TABLE_NAME + "/*", PERSON_ONE_RECORD);
	}

	@Override
	public boolean onCreate() {
		Log.i(TAG, "PersonProvider被创建 了");
		mHelper = new DBHelper(getContext());
		mDb = mHelper.getReadableDatabase();
		return false;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Cursor cursor = null;
		switch (mUriMatcher.match(uri)) {
		// 查询全部记录
		case PERSON_ALL_RECORDS:

			// 查询一条记录
		case PERSON_ONE_RECORD:
			cursor = mDb.query(TABLE_NAME, projection, selection,
					selectionArgs, null, null, null);
			break;
		// 未匹配到合适的uri
		default:
			throw new IllegalArgumentException("未匹配到合适的uri");
		}
		return cursor;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		switch (mUriMatcher.match(uri)) {
		case PERSON_ALL_RECORDS:

		case PERSON_ONE_RECORD:
			mDb.insert(TABLE_NAME, "id", values);
			break;
		default:
			throw new IllegalArgumentException("未匹配到合适的uri");
		}
		return uri;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int result = 0;
		switch (mUriMatcher.match(uri)) {
		case PERSON_ALL_RECORDS:

		case PERSON_ONE_RECORD:
			result = mDb.delete(TABLE_NAME, selection, selectionArgs);
			break;

		default:
			throw new IllegalArgumentException("未匹配到合适的uri");
		}
		return result;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		switch (mUriMatcher.match(uri)) {
		case PERSON_ALL_RECORDS:

		case PERSON_ONE_RECORD:
			mDb.update(TABLE_NAME, values, selection, selectionArgs);
			break;

		default:
			throw new IllegalArgumentException("未匹配到合适的uri");
		}
		return 0;
	}
}

3,测试封装结果

package com.contentprovider.demo;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.contentprovider.db.DBHelper;
import com.example.contentproviderdemo.R;

public class MainActivity extends Activity implements OnClickListener {
	private static final String TABLE_NAME = "person";
	private static final String AUTHORITY = "com.contentprovider.provider";
	private static final String TAG = "MainActivity";

	private Uri mBaseUri = Uri.parse("content://" + AUTHORITY + "/"
			+ TABLE_NAME);
	private Button mBtSingleQuery;
	private Button mBtMutiQuery;
	private Button mBtSingleDelete;
	private Button mBtMutiDelete;
	private Button mBtMutiInsert;
	private Button mBtSingleInsert;
	private Button mBtMutiUpdate;
	private Button mBtSingleUpdate;

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

	private void initView() {
		mBtSingleQuery = (Button) findViewById(R.id.bt_single_query);
		mBtMutiQuery = (Button) findViewById(R.id.bt_muti_query);

		mBtSingleDelete = (Button) findViewById(R.id.bt_single_delete);
		mBtMutiDelete = (Button) findViewById(R.id.bt_muti_delete);

		mBtMutiInsert = (Button) findViewById(R.id.bt_muti_insert);
		mBtSingleInsert = (Button) findViewById(R.id.bt_single_insert);
		mBtMutiUpdate = (Button) findViewById(R.id.bt_muti_update);
		mBtSingleUpdate = (Button) findViewById(R.id.bt_single_update);

		mBtSingleQuery.setOnClickListener(this);
		mBtMutiQuery.setOnClickListener(this);
		mBtSingleDelete.setOnClickListener(this);
		mBtMutiDelete.setOnClickListener(this);
		mBtMutiInsert.setOnClickListener(this);
		mBtSingleInsert.setOnClickListener(this);
		mBtMutiUpdate.setOnClickListener(this);
		mBtSingleUpdate.setOnClickListener(this);
	}

	private void queryOneRecord() {
		Uri uri = Uri.withAppendedPath(mBaseUri, "/" + 3);
		String sub = uri.toString().substring(
				uri.toString().lastIndexOf("/") + 1);
		Log.i(TAG, "sub = " + sub);
		Cursor cursor = getContentResolver().query(uri, null, "id=?",
				new String[] { sub }, null);
		int countColumns = cursor.getColumnCount();
		while (cursor.moveToNext()) {
			for (int i = 0; i < countColumns; i++) {
				Log.i(TAG, "单行:" + cursor.getString(i));
			}
		}
		cursor.close();

	}

	private void queryAllRecords() {
		Cursor cursor = getContentResolver().query(mBaseUri, null, null, null,
				null);
		int countColumns = cursor.getColumnCount();
		while (cursor.moveToNext()) {
			for (int i = 1; i < countColumns; i++) {
				Log.i(TAG,
						"行:" + cursor.getString(0) + "----->"
								+ cursor.getString(i));
			}
			Log.i(TAG, "================================");
		}
		cursor.close();
	}

	private int deleteMutiRecords() {
		int result = getContentResolver().delete(mBaseUri, null, null);
		return result;
	}

	private int deleteSingleRecord() {
		Uri uri = Uri.withAppendedPath(mBaseUri, "/" + 3);
		String sub = uri.toString().substring(
				uri.toString().lastIndexOf("/") + 1);
		return getContentResolver().delete(uri, "id=?", new String[] { sub });
	}

	private void insertSingleRecord() {
		Uri uri = Uri.withAppendedPath(mBaseUri, "/" + 11);
		ContentValues values = new ContentValues();
		values.put("name", "fengqingyang");
		values.put("sex", "female");
		values.put("age", 40);
		getContentResolver().insert(uri, values);
	}

	private void insertMutiRecords() {
		ContentValues values = new ContentValues();
		for (int i = 60; i < 70; i++) {
			values.put("name", "fengqingyang" + i);
			values.put("sex", "female");
			values.put("age", i);
			getContentResolver().insert(mBaseUri, values);
			values.clear();
		}

	}

	private void updateSingleRecord() {
		ContentValues values = new ContentValues();
		values.put("name", "linghuchong");
		values.put("sex", "female");
		values.put("age", 45);
		getContentResolver().update(mBaseUri, values , "id=?", new String[]{"5"});
	}

	private void updateMutiRecords() {
		ContentValues values = new ContentValues();
		for(int i=0; i<3; i++){
			values.put("name", "renyingying"+i);
			values.put("sex", "male");
			values.put("age", 55+i);
			getContentResolver().update(mBaseUri, values , "id=?", new String[]{(i+1)+""});
			values.clear();
		}
	}

	@Override
	public void onClick(View v) {
		int result = -1;
		switch (v.getId()) {
		case R.id.bt_single_query:
			queryOneRecord();
			break;

		case R.id.bt_muti_query:
			queryAllRecords();
			break;

		case R.id.bt_single_delete:
			result = deleteSingleRecord();
			Log.i(TAG, "影响的行数::" + result);
			Log.i(TAG, "再次查询看结果");
			queryAllRecords();
			break;

		case R.id.bt_muti_delete:
			result = deleteMutiRecords();
			Log.i(TAG, "影响的行数::" + result);
			Log.i(TAG, "再次查询看结果");
			queryAllRecords();
			break;

		case R.id.bt_single_insert:
			insertSingleRecord();
			Log.i(TAG, "查看单行结果插入");
			queryAllRecords();
			break;

		case R.id.bt_muti_insert:
			insertMutiRecords();
			Log.i(TAG, "查看多行结果插入");
			queryAllRecords();
			break;

		case R.id.bt_muti_update:
			Log.i(TAG,"多行更新前");
			queryAllRecords();
			Log.i(TAG,"多行更新后");
			updateMutiRecords();
			queryAllRecords();
			break;

		case R.id.bt_single_update:
			Log.i(TAG,"单行更新前");
			queryAllRecords();
			Log.i(TAG,"单行更新后");
			updateSingleRecord();
			queryAllRecords();
			break;
		default:
			break;
		}
	}
}

工程下载地址: http://download.csdn.net/detail/qizhukanhai2/7191111

你可能感兴趣的:(android)