关于android:Android基础知识梳理四大组件之Content-Provider

31次阅读

共计 4226 个字符,预计需要花费 11 分钟才能阅读完成。

定义

ContentProvider顾名思义就是内容提供者,通过屏蔽底层过程间通信的具体实现,为不同利用之间的数据共享提供对立的接口。用户能够灵便的实现 ContentProvider 封装的数据存储和增删改查接口。

  • ContentProvider中应用 URI 拜访数据,URI 格局如下:

    [scheme://][host:port][path][?query]

    content://com.example.provider/person

应用

1. 在 AndroidManifest.xml 注册

<provider
    android:authorities="com.example.provider"
    android:name=".ExampleContentProvider"
    android:exported="true"/>
  • 其中 authorities 字段即为以后 ContentProvider 的惟一标识,拜访 URI 为 content://com.example.provider

2. 代码实现

(1)定义数据库操作类

public class DbHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "person.db";

    private static final int DB_VERSION = 1;

    private static final String TABLE_NAME = "person";

    private static final String ID = "_id";
    
    private static final String NAME = "name";

    public DbHelper(Context context) {super(context, DB_NAME, null, DB_VERSION);

    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE" + TABLE_NAME + "(" + ID
                + "INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" + "," + NAME
                + "CHAR(10) )";
        db.execSQL(sql);
    }

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

(2)实现ContentProvider

public class ExampleContentProvider extends ContentProvider {
    private SQLiteDatabase db;
    private static final String MAUTHORITIESNAME = "com.example.provider";
    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int PERSON = 1;
    private static final int PERSON_NUMBER = 2;
    private static final int PERSON_TEXT = 3;
    private static final String TABLE_NAME = "person";

    // 构建 URI
    static {
        // content://com.example.provider/person
        matcher.addURI(MAUTHORITIESNAME, "person", PERSON);
        // # 代表任意数字 content://com.example.provider/person/1
        matcher.addURI(MAUTHORITIESNAME, "person/#", PERSON_NUMBER);
        // * 代表任意文本 content://com.example.provider/person/filter/personXxx
        matcher.addURI(MAUTHORITIESNAME, "person/filter/*", PERSON_TEXT);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        // Implement this to handle requests for the MIME type of the data
        // at the given URI.
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // Implement this to handle requests to insert a new row.
        int match = matcher.match(uri);
        switch (match) {
            case PERSON:
                long id = db.insert(TABLE_NAME, null, values);
                return ContentUris.withAppendedId(uri, id);
            case PERSON_NUMBER:
            case PERSON_TEXT:
            default:
                break;
        }
        return null;
    }

    @Override
    public boolean onCreate() {
        // Implement this to initialize your content provider on startup.
        DbHelper dbHelper = new DbHelper(getContext());
        db = dbHelper.getWritableDatabase();
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // Implement this to handle query requests from clients.
        int match = matcher.match(uri);
        switch (match) {
            case PERSON:
                db.query(TABLE_NAME, projection, selection, selectionArgs, null ,null, sortOrder);
            case PERSON_NUMBER:
            case PERSON_TEXT:
            default:
                break;
        }
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // Implement this to handle requests to update one or more rows.
       return 0;
    }
}

(3)通过 ContentResolver 调用 ContentProvider 拜访数据库

private String uri = "content://com.example.provider/person";
public String queryPersonName() {
    String name = null;
    Cursor cursor = getContentResolver().query(Uri.parse(uri), null, null, null, null);
    while (cursor.moveToNext()) {name = cursor.getString(cursor.getColumnIndex("name"));
    }
    return name;
}

public void insertPerson(String name) {ContentValues values = new ContentValues();
    values.put("name", name);
    Uri result = getContentResolver().insert(Uri.parse(uri), values);
    long parseid = ContentUris.parseId(result);
    if (parseid > 0) {// insert success}
}

内容解决者 ContentResolver

ContentResolver通过 URI 调用 getContentResolver() 获取ContentProvider 提供的数据接口,进而进行增删改查等操作。

getContentResolver().query(Uri.parse(uri), null, null, null, null);

内容观察者 ContentObserver

ContentObserver 内容观察者通过指定 URI 监听ContentProvider 数据是否扭转。

1. 注册 ContentObserver

private void registerContentObserver() {Uri uri = Uri.parse("content://com.example.provider/person");
    getContentResolver().registerContentObserver(uri, true,
            new ExampleContentObserver(new Handler()));
}

2. 监听内容变动

public class ExampleContentObserver extends ContentObserver {private static final String TAG = ExampleContentObserver.class.getSimpleName();
    
    public ExampleContentObserver(Handler handler) {super(handler);
    }

    @Override
    public void onChange(boolean selfChange) {super.onChange(selfChange);
        Log.i(TAG, "content has been changed");
    }
}

正文完
 0