ContentProvider-----一个完整的样例(一)

这篇博客介绍了Android的ContentProvider组件,用于处理复杂的DB数据。内容包括使用ContentProvider创建员工管理数据库,实现增删查改操作。文章提供了一个用户界面截图和四个关键代码文件:Employees.java, DBHelper.java, EmployeeProvider.java, ContentProviderFullDemoActivity.java,并给出了源码下载链接。" 95456290,5755489,RocketMQ消息发送详解:同步、异步与单向,"['消息队列', 'RocketMQ', '消息发送', '分布式']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ContentProvider

    ContentProvider  是Android的四大组件之一,对于许多比较复杂的数据的处理,许多APP都是采用ContentProvider,来创建一个DB数据库,从而可以统一对DB数据进行处理。

   下面的这个样例,是创建一个员工管理的DB数据库,员工信息包括姓名,年龄,性别。我们可以对这个DB数据库进行基本的增,删,查,改操作。


用户界面如下图:




关键的代码:

1.Employees.java

public class Employees {

    public static final String AUTHORITY = "com.konka.provider.Employees";
    
    private Employees() {}
    
    // 内部类
    public static final class Employee implements BaseColumns {
        
    	// 构造方法
        private Employee() {}
        
        // 访问Uri
        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/employee");
        
        // 内容类型
        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.amaker.employees";
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.amaker.employees";
        
        // 默认排序常量
        public static final String DEFAULT_SORT_ORDER = "name DESC";// 按姓名排序
        
        // 表字段常量
        public static final String NAME = "name";                    // 姓名
        public static final String GENDER= "gender";                // 性别
        public static final String AGE = "age";                     // 年龄
    }		
}

2.DBHelper.java

/**
 * 
 * 数据库工具类
 */
public class DBHelper extends SQLiteOpenHelper{
    
	// 数据库名称常量
    private static final String DATABASE_NAME = "Employees.db";
    
    // 数据库版本常量
    private static final int DATABASE_VERSION = 1;
    
    // 表名称常量
    public static final String EMPLOYEES_TABLE_NAME = "employee";
    
    
    // 构造方法
    public DBHelper(Context context) {
        // 创建数据库
        super(context, DATABASE_NAME,null, DATABASE_VERSION);
    }

    
    // 创建时调用
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + EMPLOYEES_TABLE_NAME + " ("
                + Employee._ID + " INTEGER PRIMARY KEY,"
                + Employee.NAME + " TEXT,"
                + Employee.GENDER + " TEXT,"
                + Employee.AGE + " INTEGER"
                + ");");
    }

    
    // 版本更新时调用
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 删除表
        db.execSQL("DROP TABLE IF EXISTS employee");
        onCreate(db);
    }
}

3.EmployeeProvider.java

public class EmployeeProvider extends ContentProvider{

	// 数据库帮助类
    private DBHelper dbHelper = null;
    
    // Uri工具类
    private static final UriMatcher sUriMatcher;
    
    // 查询、更新条件
    private static final int EMPLOYEE = 1;
    private static final int EMPLOYEE_ID = 2;
    
    // 查询列集合
    private static HashMap<String, String> empProjectionMap;
    
    static {
        // Uri匹配工具类
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Employees.AUTHORITY, "employee", EMPLOYEE);
        sUriMatcher.addURI(Employees.AUTHORITY, "employee/#", EMPLOYEE_ID);
        // 实例化查询列集合
        empProjectionMap = new HashMap<String, String>();
        // 添加查询列
        empProjectionMap.put(Employee._ID, Employee._ID);
        empProjectionMap.put(Employee.NAME, Employee.NAME);
        empProjectionMap.put(Employee.GENDER, Employee.GENDER);
        empProjectionMap.put(Employee.AGE, Employee.AGE);
    }

    
    // 创建是调用
    public boolean onCreate() {
        // 实例化数据库帮助类
        dbHelper = new DBHelper(getContext());
        return true;
    }
    
    
    // 添加方法
    public Uri insert(Uri uri, ContentValues values) {
        // 获得数据库实例
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // 插入数据,返回行ID
        long rowId = db.insert(DBHelper.EMPLOYEES_TABLE_NAME, Employee.NAME, values);
        // 如果插入成功返回uri
        if (rowId > 0) {
            Uri empUri = ContentUris.withAppendedId(Employee.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(empUri, null);
            return empUri;
        }
        return null;
    }
    
    // 删除方法
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // 获得数据库实例
        SQLiteDatabase db = dbHelper.getWritableDatabase();
         // 获得数据库实例
        int count;
        switch (sUriMatcher.match(uri)) {
        // 根据指定条件删除
        case EMPLOYEE:
            count = db.delete(DBHelper.EMPLOYEES_TABLE_NAME, selection, selectionArgs);
            break;
        // 根据指定条件和ID删除
        case EMPLOYEE_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.delete(DBHelper.EMPLOYEES_TABLE_NAME, Employee._ID + "=" + noteId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("错误的 URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    
    // 获得类型
    public String getType(Uri uri) {
        return null;
    }

    
    // 查询方法
    public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
         SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
            switch (sUriMatcher.match(uri)) {
            // 查询所有
            case EMPLOYEE:
                qb.setTables(DBHelper.EMPLOYEES_TABLE_NAME);
                qb.setProjectionMap(empProjectionMap);
                break;
            // 根据ID查询
            case EMPLOYEE_ID:
                qb.setTables(DBHelper.EMPLOYEES_TABLE_NAME);
                qb.setProjectionMap(empProjectionMap);
                qb.appendWhere(Employee._ID + "=" + uri.getPathSegments().get(1));
                break;
            default:
                throw new IllegalArgumentException("Uri错误! " + uri);
            }

            // 使用默认排序
            String orderBy;
            if (TextUtils.isEmpty(sortOrder)) {
                orderBy = Employee.DEFAULT_SORT_ORDER;
            } else {
                orderBy = sortOrder;
            }

            // 获得数据库实例
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            // 返回游标集合
            Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
            c.setNotificationUri(getContext().getContentResolver(), uri);
            return c;
    }

    
    // 更新方法
    public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {
        // 获得数据库实例
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        // 根据指定条件更新
        case EMPLOYEE:
            count = db.update(DBHelper.EMPLOYEES_TABLE_NAME, values, selection, selectionArgs);
            break;
        // 根据指定条件和ID更新
        case EMPLOYEE_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.update(DBHelper.EMPLOYEES_TABLE_NAME, values, Employee._ID + "=" + noteId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("错误的 URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }	
}

4.ContentProviderFullDemoActivity.java

public class ContentProviderFullDemoActivity extends Activity implements OnClickListener {
	
	public static String TAG = "ContentProviderFullDemoActivity";
	
	public Uri uri = Employee.CONTENT_URI;
    
	private Button insertData = null;
	private Button queryData = null;
	private Button deleteData = null;
	private Button updateData = null;
	
		
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        
        insertData = (Button) findViewById(R.id.insertData);
        insertData.setOnClickListener(ContentProviderFullDemoActivity.this);
        
        queryData = (Button) findViewById(R.id.queryData);
        queryData.setOnClickListener(ContentProviderFullDemoActivity.this);
        
        deleteData = (Button) findViewById(R.id.deleteData);
        deleteData.setOnClickListener(ContentProviderFullDemoActivity.this);
        
        updateData = (Button) findViewById(R.id.updateData);
        updateData.setOnClickListener(ContentProviderFullDemoActivity.this);                      
    }
     
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub		
		if(view == insertData){
						
	        ContentValues values = new ContentValues();
	        values.put(Employee.NAME, "amaker");
	        values.put(Employee.GENDER, "male");
	        values.put(Employee.AGE,30);
			
			// 插入
			insert(uri,values);
			Log.i(TAG, "insert");
			
		}else if(view == queryData){
			
			// 查询
			query();
			Log.i(TAG, "query");
			
		}else if(view == deleteData){
			
			//这是删除名字为:amaker的数据的方法:
	        String[] deleteValue = {"amaker"};
			String where = "name";
									
			// 删除
	        del(uri,where,deleteValue);
	        Log.i(TAG, "del");
	        
		}else if(view == updateData){
			
			ContentValues values = new ContentValues();
			values.put(Employee.NAME, "testUpdate");
			values.put(Employee.GENDER, "female");
			values.put(Employee.AGE,39);
						
			String where = "name";
			String[] selectValue = {"amaker"};
			
			// 更新
	        update(uri,values,where,selectValue);
	        Log.i(TAG, "update");
		}	
	}
	
	
	  // 插入
    private void insert(Uri uri, ContentValues values){
        getContentResolver().insert(uri, values);
    }
	
    
    // 查询
    private void query(){
        // 查询列数组
           String[] PROJECTION = new String[] { 
                   Employee._ID,         // 0
                   Employee.NAME,         // 1
                   Employee.GENDER,     // 2
                   Employee.AGE         // 3
        };
        // 查询所有备忘录信息
        Cursor cursor = getContentResolver().query(Employee.CONTENT_URI,PROJECTION, null, null,Employee.DEFAULT_SORT_ORDER);
        //Cursor c = managedQuery(Employee.CONTENT_URI, PROJECTION, null,null, Employee.DEFAULT_SORT_ORDER);
        if (cursor.moveToFirst()) {
            // 遍历游标
            for (int i = 0; i < cursor.getCount(); i++) {
            	cursor.moveToPosition(i);

                String name = cursor.getString(1);
                String gender = cursor.getString(2);
                int age = cursor.getInt(3);

                Log.i(TAG, "db第"+i+"个数据:"+"--name:"+name+"--gender:"+gender+"--age:"+age);
            }
        }
        cursor.close();
    }
	
	
	// 删除方法
    private void del(Uri uri,String where, String[] deleteValue){
    	   	
    	/****  删除ID为1的记录的方法:
    	 
        // 删除ID为1的记录
        Uri uri = ContentUris.withAppendedId(Employee.CONTENT_URI, 1);
        // 获得ContentResolver,并删除
        getContentResolver().delete(uri, null, null);
        
        ****/
    	
        getContentResolver().delete(uri, where+"=?", deleteValue);
    }
    
    // 更新
    private void update(Uri uri, ContentValues values, String where, String[] selectValue){
    	
    	/**************************************************************
        // 更新ID为1的记录
    	Uri uri = ContentUris.withAppendedId(Employee.CONTENT_URI, 1);
        
        ContentValues values = new ContentValues();
        // 添加员工信息
        values.put(Employee.NAME, "hz.guo");
        values.put(Employee.GENDER, "male");
        values.put(Employee.AGE,31);
        
        // 获得ContentResolver,并更新
        getContentResolver().update(uri, values, null, null);
        *************************************************************/

        //getContentResolver().update(uri, values, "name"+"=?", selectValue);
    	getContentResolver().update(uri, values, where+"=?", selectValue);
    }
}


源码下载地址:

http://download.youkuaiyun.com/detail/hfreeman2011/5041208


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值