• android ContentProvider


       内容提供者对外提供共享数据,需要在清单文件中进行配置,必须在应用的包或者子包下。

    ContentProvider类

    public class PersonProvider extends ContentProvider //必须继承ContentProvider类
    {
    private DBOpenHelper dbOpenHelper; private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH); private static final int PERSONS = 1; private static final int PERSON = 2; static{ MATCHER.addURI("cn.itcast.providers.personprovider", "person", PERSONS); MATCHER.addURI("cn.itcast.providers.personprovider", "person/#", PERSON); } @Override public boolean onCreate() { dbOpenHelper = new DBOpenHelper(this.getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); switch (MATCHER.match(uri)) { case PERSONS: return db.query("person", projection, selection, selectionArgs, null, null, sortOrder); case PERSON: long rowid = ContentUris.parseId(uri); String where = "personid="+ rowid; if(selection!=null && !"".equals(selection.trim())){ where += " and "+ selection; } return db.query("person", projection, where, selectionArgs, null, null, sortOrder); default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } } @Override public String getType(Uri uri) { switch (MATCHER.match(uri)) { case PERSONS: return "vnd.android.cursor.dir/person"; case PERSON: return "vnd.android.cursor.item/person"; default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); switch (MATCHER.match(uri)) { case PERSONS: long rowid = db.insert("person", "name", values);//主键值 // content://cn.itcast.provides.personprovider/person/10 Uri insertUri = ContentUris.withAppendedId(uri, rowid); this.getContext().getContentResolver().notifyChange(uri, null);//发出数据变化通知 return insertUri; default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int num = 0; switch (MATCHER.match(uri)) { case PERSONS: num = db.delete("person", selection, selectionArgs); break; case PERSON: long rowid = ContentUris.parseId(uri); String where = "personid="+ rowid; if(selection!=null && !"".equals(selection.trim())){ where += " and "+ selection; } num = db.delete("person", where, selectionArgs); break; default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } return num; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int num = 0; switch (MATCHER.match(uri)) { case PERSONS: num = db.update("person", values, selection, selectionArgs); break; case PERSON: long rowid = ContentUris.parseId(uri); String where = "personid="+ rowid; if(selection!=null && !"".equals(selection.trim())){ where += " and "+ selection; } num = db.update("person", values, where, selectionArgs); break; default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } return num; } }

    清单文件配置:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="cn.itcast.db"
          android:versionCode="1"
          android:versionName="1.0">
        <application android:icon="@drawable/icon" android:label="@string/app_name">
            <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>
    <uses-library android:name="android.test.runner" />
    
            <provider android:name=".PersonProvider" android:authorities="cn.itcast.providers.personprovider"/>
        </application>
        <uses-sdk android:minSdkVersion="8" />
    
    <instrumentation android:name="android.test.InstrumentationTestRunner"
      android:targetPackage="cn.itcast.db" android:label="Tests for My App" />
      
    </manifest> 

    对内容提供者的使用:

    public class AccessContentProviderTest extends AndroidTestCase {
        private static final String TAG = "AccessContentProviderTest";
        
        public void testInsert() throws Exception{                                       
            Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person");
            ContentResolver resolver = this.getContext().getContentResolver();
            ContentValues values = new ContentValues();
            values.put("name", "laoli");
            values.put("phone", "1860103838383");
            values.put("amount", "50000000000");
            resolver.insert(uri, values);
        }
        
        public void testDelete() throws Exception{
            Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person/20");
            ContentResolver resolver = this.getContext().getContentResolver();
            resolver.delete(uri, null, null);
        }
        
        public void testUpdate() throws Exception{
            Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person/1");
            ContentResolver resolver = this.getContext().getContentResolver();
            ContentValues values = new ContentValues();
            values.put("name", "zhangxiaoxiao");
            resolver.update(uri, values, null, null);
        }
        
        public void testQuery() throws Exception{
            Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person");
            ContentResolver resolver = this.getContext().getContentResolver();
            Cursor cursor = resolver.query(uri, null, null, null, "personid asc");
            while(cursor.moveToNext()){
                String name = cursor.getString(cursor.getColumnIndex("name"));
                Log.i(TAG, name);
            }
            cursor.close();
        }
    }

     监听内容提供者的数据的变化:

    1、打开数据变化的通知:

    2、注册数据变化监听

     内容提供者中多个操作在同一个事物中执行:

  • 相关阅读:
    pl/sql 导入csv到oracle时乱码问题
    mybatis if判断两个值是否相等存在的坑啊
    mybatis #与$占位符的区别
    NPM使用前设置和升级
    AWS ec2的ubuntu14.04上安装git服务
    Apache性能优化
    i5+GT730+B85安装OSX10.10.5 (Yosemite Install(14F27).cdr)
    IE的css hack
    sourcetree(mac)设置代理
    webpack配置的说明
  • 原文地址:https://www.cnblogs.com/heml/p/3510466.html
Copyright © 2020-2023  润新知