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

来源:互联网 发布:王保保 知乎 编辑:程序博客网 时间:2024/06/03 21:32
ContentProvider

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

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


用户界面如下图:




关键的代码:

1.Employees.java

[java] view plain copy
  1. public class Employees {  
  2.   
  3.     public static final String AUTHORITY = "com.konka.provider.Employees";  
  4.       
  5.     private Employees() {}  
  6.       
  7.     // 内部类  
  8.     public static final class Employee implements BaseColumns {  
  9.           
  10.         // 构造方法  
  11.         private Employee() {}  
  12.           
  13.         // 访问Uri  
  14.         public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/employee");  
  15.           
  16.         // 内容类型  
  17.         public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.amaker.employees";  
  18.         public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.amaker.employees";  
  19.           
  20.         // 默认排序常量  
  21.         public static final String DEFAULT_SORT_ORDER = "name DESC";// 按姓名排序  
  22.           
  23.         // 表字段常量  
  24.         public static final String NAME = "name";                    // 姓名  
  25.         public static final String GENDER= "gender";                // 性别  
  26.         public static final String AGE = "age";                     // 年龄  
  27.     }         
  28. }  

2.DBHelper.java

[java] view plain copy
  1. /** 
  2.  *  
  3.  * 数据库工具类 
  4.  */  
  5. public class DBHelper extends SQLiteOpenHelper{  
  6.       
  7.     // 数据库名称常量  
  8.     private static final String DATABASE_NAME = "Employees.db";  
  9.       
  10.     // 数据库版本常量  
  11.     private static final int DATABASE_VERSION = 1;  
  12.       
  13.     // 表名称常量  
  14.     public static final String EMPLOYEES_TABLE_NAME = "employee";  
  15.       
  16.       
  17.     // 构造方法  
  18.     public DBHelper(Context context) {  
  19.         // 创建数据库  
  20.         super(context, DATABASE_NAME,null, DATABASE_VERSION);  
  21.     }  
  22.   
  23.       
  24.     // 创建时调用  
  25.     public void onCreate(SQLiteDatabase db) {  
  26.         db.execSQL("CREATE TABLE " + EMPLOYEES_TABLE_NAME + " ("  
  27.                 + Employee._ID + " INTEGER PRIMARY KEY,"  
  28.                 + Employee.NAME + " TEXT,"  
  29.                 + Employee.GENDER + " TEXT,"  
  30.                 + Employee.AGE + " INTEGER"  
  31.                 + ");");  
  32.     }  
  33.   
  34.       
  35.     // 版本更新时调用  
  36.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  37.         // 删除表  
  38.         db.execSQL("DROP TABLE IF EXISTS employee");  
  39.         onCreate(db);  
  40.     }  
  41. }  

3.EmployeeProvider.java

[java] view plain copy
  1. public class EmployeeProvider extends ContentProvider{  
  2.   
  3.     // 数据库帮助类  
  4.     private DBHelper dbHelper = null;  
  5.       
  6.     // Uri工具类  
  7.     private static final UriMatcher sUriMatcher;  
  8.       
  9.     // 查询、更新条件  
  10.     private static final int EMPLOYEE = 1;  
  11.     private static final int EMPLOYEE_ID = 2;  
  12.       
  13.     // 查询列集合  
  14.     private static HashMap<String, String> empProjectionMap;  
  15.       
  16.     static {  
  17.         // Uri匹配工具类  
  18.         sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);  
  19.         sUriMatcher.addURI(Employees.AUTHORITY, "employee", EMPLOYEE);  
  20.         sUriMatcher.addURI(Employees.AUTHORITY, "employee/#", EMPLOYEE_ID);  
  21.         // 实例化查询列集合  
  22.         empProjectionMap = new HashMap<String, String>();  
  23.         // 添加查询列  
  24.         empProjectionMap.put(Employee._ID, Employee._ID);  
  25.         empProjectionMap.put(Employee.NAME, Employee.NAME);  
  26.         empProjectionMap.put(Employee.GENDER, Employee.GENDER);  
  27.         empProjectionMap.put(Employee.AGE, Employee.AGE);  
  28.     }  
  29.   
  30.       
  31.     // 创建是调用  
  32.     public boolean onCreate() {  
  33.         // 实例化数据库帮助类  
  34.         dbHelper = new DBHelper(getContext());  
  35.         return true;  
  36.     }  
  37.       
  38.       
  39.     // 添加方法  
  40.     public Uri insert(Uri uri, ContentValues values) {  
  41.         // 获得数据库实例  
  42.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  43.         // 插入数据,返回行ID  
  44.         long rowId = db.insert(DBHelper.EMPLOYEES_TABLE_NAME, Employee.NAME, values);  
  45.         // 如果插入成功返回uri  
  46.         if (rowId > 0) {  
  47.             Uri empUri = ContentUris.withAppendedId(Employee.CONTENT_URI, rowId);  
  48.             getContext().getContentResolver().notifyChange(empUri, null);  
  49.             return empUri;  
  50.         }  
  51.         return null;  
  52.     }  
  53.       
  54.     // 删除方法  
  55.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  56.         // 获得数据库实例  
  57.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  58.          // 获得数据库实例  
  59.         int count;  
  60.         switch (sUriMatcher.match(uri)) {  
  61.         // 根据指定条件删除  
  62.         case EMPLOYEE:  
  63.             count = db.delete(DBHelper.EMPLOYEES_TABLE_NAME, selection, selectionArgs);  
  64.             break;  
  65.         // 根据指定条件和ID删除  
  66.         case EMPLOYEE_ID:  
  67.             String noteId = uri.getPathSegments().get(1);  
  68.             count = db.delete(DBHelper.EMPLOYEES_TABLE_NAME, Employee._ID + "=" + noteId  
  69.                     + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);  
  70.             break;  
  71.   
  72.         default:  
  73.             throw new IllegalArgumentException("错误的 URI " + uri);  
  74.         }  
  75.         getContext().getContentResolver().notifyChange(uri, null);  
  76.         return count;  
  77.     }  
  78.   
  79.       
  80.     // 获得类型  
  81.     public String getType(Uri uri) {  
  82.         return null;  
  83.     }  
  84.   
  85.       
  86.     // 查询方法  
  87.     public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {  
  88.          SQLiteQueryBuilder qb = new SQLiteQueryBuilder();  
  89.             switch (sUriMatcher.match(uri)) {  
  90.             // 查询所有  
  91.             case EMPLOYEE:  
  92.                 qb.setTables(DBHelper.EMPLOYEES_TABLE_NAME);  
  93.                 qb.setProjectionMap(empProjectionMap);  
  94.                 break;  
  95.             // 根据ID查询  
  96.             case EMPLOYEE_ID:  
  97.                 qb.setTables(DBHelper.EMPLOYEES_TABLE_NAME);  
  98.                 qb.setProjectionMap(empProjectionMap);  
  99.                 qb.appendWhere(Employee._ID + "=" + uri.getPathSegments().get(1));  
  100.                 break;  
  101.             default:  
  102.                 throw new IllegalArgumentException("Uri错误! " + uri);  
  103.             }  
  104.   
  105.             // 使用默认排序  
  106.             String orderBy;  
  107.             if (TextUtils.isEmpty(sortOrder)) {  
  108.                 orderBy = Employee.DEFAULT_SORT_ORDER;  
  109.             } else {  
  110.                 orderBy = sortOrder;  
  111.             }  
  112.   
  113.             // 获得数据库实例  
  114.             SQLiteDatabase db = dbHelper.getReadableDatabase();  
  115.             // 返回游标集合  
  116.             Cursor c = qb.query(db, projection, selection, selectionArgs, nullnull, orderBy);  
  117.             c.setNotificationUri(getContext().getContentResolver(), uri);  
  118.             return c;  
  119.     }  
  120.   
  121.       
  122.     // 更新方法  
  123.     public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {  
  124.         // 获得数据库实例  
  125.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  126.         int count;  
  127.         switch (sUriMatcher.match(uri)) {  
  128.         // 根据指定条件更新  
  129.         case EMPLOYEE:  
  130.             count = db.update(DBHelper.EMPLOYEES_TABLE_NAME, values, selection, selectionArgs);  
  131.             break;  
  132.         // 根据指定条件和ID更新  
  133.         case EMPLOYEE_ID:  
  134.             String noteId = uri.getPathSegments().get(1);  
  135.             count = db.update(DBHelper.EMPLOYEES_TABLE_NAME, values, Employee._ID + "=" + noteId  
  136.                     + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);  
  137.             break;  
  138.         default:  
  139.             throw new IllegalArgumentException("错误的 URI " + uri);  
  140.         }  
  141.         getContext().getContentResolver().notifyChange(uri, null);  
  142.         return count;  
  143.     }     
  144. }  

4.ContentProviderFullDemoActivity.java

[java] view plain copy
  1. public class ContentProviderFullDemoActivity extends Activity implements OnClickListener {  
  2.       
  3.     public static String TAG = "ContentProviderFullDemoActivity";  
  4.       
  5.     public Uri uri = Employee.CONTENT_URI;  
  6.       
  7.     private Button insertData = null;  
  8.     private Button queryData = null;  
  9.     private Button deleteData = null;  
  10.     private Button updateData = null;  
  11.       
  12.           
  13.     @Override  
  14.     public void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.main);          
  17.           
  18.         insertData = (Button) findViewById(R.id.insertData);  
  19.         insertData.setOnClickListener(ContentProviderFullDemoActivity.this);  
  20.           
  21.         queryData = (Button) findViewById(R.id.queryData);  
  22.         queryData.setOnClickListener(ContentProviderFullDemoActivity.this);  
  23.           
  24.         deleteData = (Button) findViewById(R.id.deleteData);  
  25.         deleteData.setOnClickListener(ContentProviderFullDemoActivity.this);  
  26.           
  27.         updateData = (Button) findViewById(R.id.updateData);  
  28.         updateData.setOnClickListener(ContentProviderFullDemoActivity.this);                        
  29.     }  
  30.        
  31.     @Override  
  32.     public void onClick(View view) {  
  33.         // TODO Auto-generated method stub        
  34.         if(view == insertData){  
  35.                           
  36.             ContentValues values = new ContentValues();  
  37.             values.put(Employee.NAME, "amaker");  
  38.             values.put(Employee.GENDER, "male");  
  39.             values.put(Employee.AGE,30);  
  40.               
  41.             // 插入  
  42.             insert(uri,values);  
  43.             Log.i(TAG, "insert");  
  44.               
  45.         }else if(view == queryData){  
  46.               
  47.             // 查询  
  48.             query();  
  49.             Log.i(TAG, "query");  
  50.               
  51.         }else if(view == deleteData){  
  52.               
  53.             //这是删除名字为:amaker的数据的方法:  
  54.             String[] deleteValue = {"amaker"};  
  55.             String where = "name";  
  56.                                       
  57.             // 删除  
  58.             del(uri,where,deleteValue);  
  59.             Log.i(TAG, "del");  
  60.               
  61.         }else if(view == updateData){  
  62.               
  63.             ContentValues values = new ContentValues();  
  64.             values.put(Employee.NAME, "testUpdate");  
  65.             values.put(Employee.GENDER, "female");  
  66.             values.put(Employee.AGE,39);  
  67.                           
  68.             String where = "name";  
  69.             String[] selectValue = {"amaker"};  
  70.               
  71.             // 更新  
  72.             update(uri,values,where,selectValue);  
  73.             Log.i(TAG, "update");  
  74.         }     
  75.     }  
  76.       
  77.       
  78.       // 插入  
  79.     private void insert(Uri uri, ContentValues values){  
  80.         getContentResolver().insert(uri, values);  
  81.     }  
  82.       
  83.       
  84.     // 查询  
  85.     private void query(){  
  86.         // 查询列数组  
  87.            String[] PROJECTION = new String[] {   
  88.                    Employee._ID,         // 0  
  89.                    Employee.NAME,         // 1  
  90.                    Employee.GENDER,     // 2  
  91.                    Employee.AGE         // 3  
  92.         };  
  93.         // 查询所有备忘录信息  
  94.         Cursor cursor = getContentResolver().query(Employee.CONTENT_URI,PROJECTION, nullnull,Employee.DEFAULT_SORT_ORDER);  
  95.         //Cursor c = managedQuery(Employee.CONTENT_URI, PROJECTION, null,null, Employee.DEFAULT_SORT_ORDER);  
  96.         if (cursor.moveToFirst()) {  
  97.             // 遍历游标  
  98.             for (int i = 0; i < cursor.getCount(); i++) {  
  99.                 cursor.moveToPosition(i);  
  100.   
  101.                 String name = cursor.getString(1);  
  102.                 String gender = cursor.getString(2);  
  103.                 int age = cursor.getInt(3);  
  104.   
  105.                 Log.i(TAG, "db第"+i+"个数据:"+"--name:"+name+"--gender:"+gender+"--age:"+age);  
  106.             }  
  107.         }  
  108.         cursor.close();  
  109.     }  
  110.       
  111.       
  112.     // 删除方法  
  113.     private void del(Uri uri,String where, String[] deleteValue){  
  114.               
  115.         /****  删除ID为1的记录的方法: 
  116.           
  117.         // 删除ID为1的记录 
  118.         Uri uri = ContentUris.withAppendedId(Employee.CONTENT_URI, 1); 
  119.         // 获得ContentResolver,并删除 
  120.         getContentResolver().delete(uri, null, null); 
  121.          
  122.         ****/  
  123.           
  124.         getContentResolver().delete(uri, where+"=?", deleteValue);  
  125.     }  
  126.       
  127.     // 更新  
  128.     private void update(Uri uri, ContentValues values, String where, String[] selectValue){  
  129.           
  130.         /************************************************************** 
  131.         // 更新ID为1的记录 
  132.         Uri uri = ContentUris.withAppendedId(Employee.CONTENT_URI, 1); 
  133.          
  134.         ContentValues values = new ContentValues(); 
  135.         // 添加员工信息 
  136.         values.put(Employee.NAME, "hz.guo"); 
  137.         values.put(Employee.GENDER, "male"); 
  138.         values.put(Employee.AGE,31); 
  139.          
  140.         // 获得ContentResolver,并更新 
  141.         getContentResolver().update(uri, values, null, null); 
  142.         *************************************************************/  
  143.   
  144.         //getContentResolver().update(uri, values, "name"+"=?", selectValue);  
  145.         getContentResolver().update(uri, values, where+"=?", selectValue);  
  146.     }  
  147. }  
0 0
原创粉丝点击