一丶源码见本文
二丶本节代码只是一个ContentProvide的测试就不上演示效果
三丶课程讲解
/** * 实体对象 */ public class Person { private int id; private String name; private int age; public Person() { } public Person(int age, String name) { this.age = age; this.name = name; } public Person(int age, int id, String name) { this.age = age; this.id = id; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "age=" + age + ", id=" + id + ", name='" + name + '\'' + '}'; } }
/** * 定义元数据 */ public final class PersonMetaData { public static abstract class Person implements BaseColumns { public static final String NAME = "name"; public static final String AGE = "age"; public static final String TABLE_NAME = "person"; } }这里直接把DatabaseHelp直接写在了DatabaseAdapter里面
/** * 数据库操作 */ public class DatabaseAdapter { private DatabaseHelper dbHelper; public DatabaseAdapter(Context context) { this.dbHelper = new DatabaseHelper(context); } public void save(Person person) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PersonMetaData.Person.NAME, person.getName()); values.put(PersonMetaData.Person.AGE, person.getAge()); db.insert(PersonMetaData.Person.TABLE_NAME, null, values); } public void delete(int id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String whereClause = PersonMetaData.Person._ID + "=?"; String[] whereArgs = {String.valueOf(id)}; db.delete(PersonMetaData.Person.TABLE_NAME, whereClause, whereArgs); } public void update(Person person) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PersonMetaData.Person.NAME, person.getName()); values.put(PersonMetaData.Person.AGE, person.getAge()); String whereClause = PersonMetaData.Person._ID + "=?"; String[] whereArgs = {String.valueOf(person.getId())}; db.update(PersonMetaData.Person.TABLE_NAME, values, whereClause, whereArgs); } public ArrayList<Person> findAll() { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor c = db.query(true, PersonMetaData.Person.TABLE_NAME, null, null, null, null, null, null, null); ArrayList<Person> list = new ArrayList<>(); Person p = null; while (c.moveToNext()) { p = new Person(); p.setName(c.getString(c.getColumnIndexOrThrow(PersonMetaData.Person.NAME))); p.setAge(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.Person.AGE))); p.setId(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.Person._ID))); list.add(p); } db.close(); return list; } public Person findById(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor c = db.query(PersonMetaData.Person.TABLE_NAME, null, PersonMetaData.Person._ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null); Person p = new Person(); if (c.moveToNext()) { p.setId(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.Person._ID))); p.setName(c.getString(c.getColumnIndexOrThrow(PersonMetaData.Person.NAME))); p.setAge(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.Person.AGE))); } db.close(); return p; } private static class DatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "cp.db"; private static final int VERSION = 1; private static final String CREATE_TABLE = "create table person(_id integer primary key autoincrement,name text,age int)"; private static final String DROP_TABLE = "drop table if exists person"; public DatabaseHelper(Context context) { super(context, DB_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); db.close(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DROP_TABLE); db.execSQL(CREATE_TABLE); db.close(); } } }
/** * 自定义 ContentProvider */ public class HellowContentProvider extends ContentProvider { //匹配码 private static final int MUTIPLE_CODE = 1;//返回多个记录的匹配码 private static final int SINGLE_CODE = 2; //返回单个记录的匹配码 //远程要访问的地址 主机号,别人访问时的路径 private static final String AUTHORITIES = "com.example.jin.contentp.hellowContentprovider"; //创建一个uri 的匹配器(定义传入的uri正确的格式) UriMatcher.NO_MATCH:编码号,uri匹配对时,就返回一个编码号 private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); /** * 数据类型 * text/plain image/jpg * * 1.单个的数据类型 * * * 2.多个的数据类型 */ private static final String SINGLE_TYPE = "vnd.android.cursor.item/person"; private static final String MUTIPLE_TYPE = "vnd.android.cursor.dir/person"; static { /** * 当传入的数径是: * content://com.example.jin.contentp.hellowContentprovider/person 后面没有编号,则查询所有, * 就进行匹配 * *content://com.example.jin.contentp.hellowContentprovider/person/1 1表示person表的id号,也可以传其它条件 * * 路径,表,返回的编号 */ URI_MATCHER.addURI(AUTHORITIES, "person", 1);//路么匹配对,则返回1 URI_MATCHER.addURI(AUTHORITIES, "person/#", 2);// *:匹配所有的字符, #:匹配所有的数字 匹配上,则返回2 } //数据库帮助类 private DatabaseAdapter.DatabaseHelper dbAdapter; /** * 创建 * * @return */ @Override public boolean onCreate() { //数据库帮助类对象 dbAdapter = new DatabaseAdapter.DatabaseHelper(getContext()); return true; } /** * 返回该URi 表示的数据类型 * * @param uri * @return */ @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case SINGLE_CODE: return SINGLE_TYPE; case MUTIPLE_CODE: return MUTIPLE_TYPE; } return null; } /** * 插入一个新的记录 * <p/> * 传入的 uri * content://com.example.jin.contentp.hellowContentprovider/person/4 * * @param uri * @param values * @return */ @Override public Uri insert(Uri uri, ContentValues values) { switch (URI_MATCHER.match(uri)) { case MUTIPLE_CODE: //数据库操作对象,进行保存操作 SQLiteDatabase db = dbAdapter.getWritableDatabase(); //当前插入的id值 long id = db.insert(PersonMetaData.Person.TABLE_NAME, null, values); db.close(); //将id 添加到 uri后面 ContentUris.withAppendedId(uri, id); break; } return uri; } /** * 查询符合指定条件的记录 * * @param uri * @param projection //列 * @param selection * @param selectionArgs * @param sortOrder * @return */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { switch (URI_MATCHER.match(uri)) { case SINGLE_CODE: SQLiteDatabase db = dbAdapter.getWritableDatabase(); //从 uri 中获取id long id = ContentUris.parseId(uri); //条件 selection = PersonMetaData.Person._ID + "=?"; //条件值 selectionArgs = new String[]{String.valueOf(id)}; return db.query(PersonMetaData.Person.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); case MUTIPLE_CODE: db = dbAdapter.getWritableDatabase(); return db.query(PersonMetaData.Person.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); } return null; } /** * 删除符合指定条件的记录 * <p/> * <p/> * content://com.example.jin.contentp.hellowContentprovider/person/4 * * @param uri * @param selection * @param selectionArgs * @return */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { switch (URI_MATCHER.match(uri)) { case SINGLE_CODE://单个删除 SQLiteDatabase db = dbAdapter.getWritableDatabase(); //从 uri 中获取id long id = ContentUris.parseId(uri); //条件 selection = PersonMetaData.Person._ID + "=?"; //条件值 selectionArgs = new String[]{String.valueOf(id)}; //需要得到传入的id号即可 int row = db.delete(PersonMetaData.Person.TABLE_NAME, selection, selectionArgs); db.close(); return row;//返回删除的行数 case MUTIPLE_CODE://多个删除 db = dbAdapter.getWritableDatabase(); //需要得到传入的id号即可 row = db.delete(PersonMetaData.Person.TABLE_NAME, selection, selectionArgs); db.close(); return row; } return 0; } /** * 更新指定条件的记录 * * @param uri * @param values * @param selection * @param selectionArgs * @return */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { switch (URI_MATCHER.match(uri)) { case SINGLE_CODE://单个更新 SQLiteDatabase db = dbAdapter.getWritableDatabase(); //从 uri 中获取id long id = ContentUris.parseId(uri); //条件 selection = PersonMetaData.Person._ID + "=?"; //条件值 selectionArgs = new String[]{String.valueOf(id)}; //需要得到传入的id号即可 int row = db.update(PersonMetaData.Person.TABLE_NAME, values, selection, selectionArgs); db.close(); return row;//返回更新的行数 case MUTIPLE_CODE://多个更新 db = dbAdapter.getWritableDatabase(); //需要得到传入的id号即可 row = db.update(PersonMetaData.Person.TABLE_NAME, values, selection, selectionArgs); db.close(); return row; } return 0; } }
//activity类 public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void addClick(View view) { //获取 内容提供者的接口 ContentResolver cr = this.getContentResolver(); //调用CP的添加方法 Uri uri = Uri.parse("content://com.example.jin.contentp.hellowContentprovider/person"); //要去访问ContentProvider ContentValues values = new ContentValues(); values.put(PersonMetaData.Person.NAME, "zhang"); //如果在其它工程中写成字符串,其它一样 values.put(PersonMetaData.Person.AGE, 18); //调用ContentProvider的方法进行添加 cr.insert(uri, values); } public void queryClick(View view) { ContentResolver cr = this.getContentResolver(); Uri uri = Uri.parse("content://com.example.jin.contentp.hellowContentprovider/person"); //要去访问ContentProvider,带ID号 Cursor cursor = cr.query(uri, null, null, null, null); while (cursor.moveToNext()) { System.out.print(cursor.getInt(cursor.getColumnIndexOrThrow(PersonMetaData.Person._ID))); System.out.print(cursor.getString(cursor.getColumnIndexOrThrow(PersonMetaData.Person.NAME))); System.out.print(cursor.getInt(cursor.getColumnIndexOrThrow(PersonMetaData.Person.AGE))); } cursor.close(); } public void delClick(View view) { ContentResolver cr = this.getContentResolver(); Uri uri = Uri.parse("content://com.example.jin.contentp.hellowContentprovider/person/1"); //要去访问ContentProvider,带ID号 cr.delete(uri, null, null); } public void updateClick(View view) { ContentResolver cr = this.getContentResolver(); Uri uri = Uri.parse("content://com.example.jin.contentp.hellowContentprovider/person/1"); //要去访问ContentProvider,带ID号 ContentValues values = new ContentValues(); values.put(PersonMetaData.Person.NAME, "zhang"); values.put(PersonMetaData.Person.AGE, 20); cr.update(uri, values, null, null); } }
//配置清单 <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <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:authorities="com.example.jin.contentp.hellowContentprovider" android:name=".HellowContentProvider" /> </application>
/** * 添加联系人 */ public class ContactsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contacts); } /** * 添加联系人 * @param view */ public void addClick(View view) { ContentResolver cr = this.getContentResolver(); //执行一个空值插入,目的是获取系统返回的rawContactId ContentValues values = new ContentValues(); Uri uri = cr.insert(ContactsContract.RawContacts.CONTENT_URI, values);//在contacts表中插入一行空列 long _id = ContentUris.parseId(uri);//获取插入的id //插入姓名数据 values.clear(); values.put(ContactsContract.Data.RAW_CONTACT_ID, _id);//在 data 表中插入id values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE); values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "jack"); cr.insert(ContactsContract.Data.CONTENT_URI, values); //插入电话数据 values.clear(); values.put(ContactsContract.Data.RAW_CONTACT_ID, _id); values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE); values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "00900"); values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE); cr.insert(ContactsContract.Data.CONTENT_URI, values); Toast.makeText(this, "记录已添加", Toast.LENGTH_LONG).show(); } /** * 删除联系人 * @param view */ public void deleteClick(View view) { ContentResolver cr = this.getContentResolver(); System.out.print(ContactsContract.Contacts.CONTENT_URI.toString() + "/3"); Uri uri = Uri.parse("content://com.android.contacts/contacts/3"); cr.delete(uri, null, null); Toast.makeText(this, "记录已删除", Toast.LENGTH_SHORT).show(); } /** * 更新联系人 * @param vied */ public void updateClick(View vied) { ContentResolver cr = this.getContentResolver(); ContentValues values = new ContentValues(); values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE); values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "4445"); values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE); cr.update(ContactsContract.Data.CONTENT_URI, values, "_id=1", null); Toast.makeText(this, "_id=1的记录已更新", Toast.LENGTH_SHORT).show(); } //查询联系人 public void queryClick(View view) { //获取接口 ContentResolver contentResolver = this.getContentResolver(); String id = null; String mimeType = null; //只需要从Contacts中获取Id,其他的都可以不要,通过查看上面编译的SQL语句,可以看出将第二个参数 //设置为Null ,默认返回的列非常多,是一种资源浪费 //查询 contacts表 查询出 id号 Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[]{ContactsContract.Contacts._ID}, null, null, null); while (cursor.moveToNext()) { id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); //从一个cursor获取所有的信息 //查询 data表 查询 id, Cursor contactInfoCursor = contentResolver.query( ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.CONTACT_ID,//查询联系人的id ContactsContract.Data.MIMETYPE,//类型 ContactsContract.Data.DATA1,//名字等信息 ContactsContract.Data.DATA15},//图片 ContactsContract.Data.CONTACT_ID + "=" + id, null, null); while (contactInfoCursor.moveToNext()) { mimeType = contactInfoCursor.getString( contactInfoCursor.getColumnIndex(ContactsContract.Data.MIMETYPE)); String value = contactInfoCursor.getString( contactInfoCursor.getColumnIndex(ContactsContract.Data.DATA1)); byte[] photo = contactInfoCursor.getBlob( contactInfoCursor.getColumnIndex(ContactsContract.Data.DATA15)); if (mimeType.contains("/name")) { System.out.print("姓名=" + value); } else if (mimeType.contains("/email")) { System.out.print("邮箱=" + value); } else if (mimeType.contains("/im")) { System.out.print("聊天QQ账号=" + value); } else if (mimeType.contains("/phone")) { System.out.print("电话=" + value); } else if (mimeType.contains("/postal")) { System.out.print("邮编=" + value); } else if (mimeType.contains("/photo")) { System.out.print("照片=" + photo);//图片使用ImageView来显示 } else if (mimeType.contains("/group")) { System.out.print("组=" + value); } else if (mimeType.contains("/postal-address_v2")) { System.out.print("地址=" + value); } } contactInfoCursor.close(); } cursor.close(); } }