您的位置:首页 > 移动开发 > Android开发

Android IPC机制之ContentProvider

2016-03-14 10:47 399 查看
ContentProvider:即内容提供者,用来管理数据,并对外暴露一个uri,外部可以通过uri和数据建立联系并获取或操作数据;

服务端:
1、首先创建一个数据库类,并创建一个表;
2、创建一个ContentProvider,用来操作这个数据库和表,实现增删改查和获取所有表里的数据信息;然后注册uri(对外暴露),其他客户端可以通过ContentResolver和对外暴露的uri使用ContentProvider来操作数据库并获取数据

客户端:
1、创建一个工具类,通过ContentResolver和服务端暴露的uri来和服务端建立联系,并通过服务端的ContentProvider来操作服务端的数据库并获取数据

示例代码

服务端:

首先创建一个数据库

package com.jiao.myaidl;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
* Created by jiaocg on 2016/3/12.
* 数据库类
*/
public class EmployeeDBHelper extends SQLiteOpenHelper {

private final static String DB_NAME = "myDatabase.db";//数据库名字
private final static int DB_VERSION = 1;
public final static String EMPLOYEE_TABLE_NAME = "employee";
private String CREATE_BOOK_TABLE = "CREATE TABLE IF NOT EXISTS "
+ EMPLOYEE_TABLE_NAME + " (id INTEGER PRIMARY KEY,"
+ "workNum TEXT," + "name TEXT," + "department TEXT)";

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

}

@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL(CREATE_BOOK_TABLE);
}

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

}
}


创建一个ContentProvider操作数据库

package com.jiao.myaidl;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;

/**
* Created by jiaocg on 2016/3/12.
*/
public class EmployeeProvider extends ContentProvider {

private SQLiteDatabase mDb;
private final static String AUTOORITY = "com.jiao.myaidl.employee.EmployeeProvider";
private final static int EMPLOYEE_URI_CODE = 0;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

//注册uri
static {
sUriMatcher.addURI(AUTOORITY, "employee", EMPLOYEE_URI_CODE);
}

@Override
public boolean onCreate() {

insertDataToDb();
return true;
}

@Nullable
void insertDataToDb() {

mDb = new EmployeeDBHelper(getContext()).getWritableDatabase();
mDb.execSQL("delete from " + EmployeeDBHelper.EMPLOYEE_TABLE_NAME);
mDb.execSQL("insert into employee values(1,'1001','张三','销售部');");
mDb.execSQL("insert into employee values(2,'1002','李四','人事部');");
mDb.execSQL("insert into employee values(3,'1003','王五','研发部');");
mDb.execSQL("insert into employee values(4,'1004','小明','研发部');");
mDb.execSQL("insert into employee values(5,'1005','小强','销售部');");
}

public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

String tableName = getTableName(uri);

if (tableName == null) {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
Cursor cursor = mDb.query(tableName, projection, selection, selectionArgs, null, null, sortOrder, null);
return cursor;
}

@Nullable
@Override
public String getType(Uri uri) {
return null;
}

@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
String table = getTableName(uri);
if (table == null) {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
mDb.insert(table, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
String table = getTableName(uri);
if (table == null) {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
int count = mDb.delete(table, selection, selectionArgs);
if (count > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
String table = getTableName(uri);
if (table == null) {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
int row = mDb.update(table, values, selection, selectionArgs);
if (row > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return row;
}

private String getTableName(Uri uri) {
String tableName = null;
if (sUriMatcher.match(uri) == EMPLOYEE_URI_CODE) {
tableName = EmployeeDBHelper.EMPLOYEE_TABLE_NAME;
}
return tableName;
}
}


清单文件中注册ContentProvider

 

<provider
android:name="com.jiao.myaidl.EmployeeProvider"
android:authorities="com.jiao.myaidl.employee.EmployeeProvider"
android:exported="true" />


客户端:

创建一个工具类,通过服务端暴露的uri和服务端的数据库建立联系

package com.jiao.myaidl;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import com.jiao.myaidl.entity.Employee;
import java.util.ArrayList;
import java.util.List;

/**
* Created by jiaocg on 2016/3/12.
*/
public class HandleProvider {

private static Context mContext;
private static HandleProvider mInstance;
private static Uri mEmployeeUri;
private static final String EMPLOYEE_CONTENT_URI = "content://com.jiao.myaidl.employee.EmployeeProvider/employee";

private HandleProvider(Context context) {
this.mContext = context;
mEmployeeUri = Uri.parse(EMPLOYEE_CONTENT_URI);
}

//单例
public static HandleProvider getmInstance(Context context) {
if (mInstance == null) {
synchronized (HandleProvider.class) {
if (mInstance == null) {
mInstance = new HandleProvider(context);
}
}
}

return mInstance;
}

public void delete() {
ContentResolver contentResolver = mContext.getContentResolver();
String where = "id=?";
String[] where_args = {"7"};//满足条件的 值集合
contentResolver.delete(mEmployeeUri, where, where_args);
}

public void update() {
ContentResolver contentResolver = mContext.getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "梁山伯");
String where = "id=?";
String[] where_args = {"1"};
contentResolver.update(mEmployeeUri, values, where, where_args);
}

public void create() {
ContentValues values = new ContentValues();
values.put("id", 7);
values.put("workNum", "1006");
values.put("name", "张三丰");
values.put("department", "研发部");
mContext.getContentResolver().insert(mEmployeeUri, values);
}

public List<String> query() {
List<String> list = new ArrayList<>();
Cursor cursor = mContext.getContentResolver().query(mEmployeeUri, new String[]{"id", "workNum", "name", "department"}, null, null, null);

while (cursor.moveToNext()) {
Employee employee = new Employee();
employee.setId(cursor.getInt(0));
employee.setWorkNum(cursor.getString(1));
employee.setName(cursor.getString(2));
employee.setDepartment(cursor.getString(3));
String str = employee.toString();
list.add(str);
Log.d("mainActivity", "query employee:" + str);
}
cursor.close();
return list;
}
}


主代码,获取和使用服务端的数据

package com.jiao.myaidl;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.jiao.myaidl.client.R;

import java.util.List;

public class EmployeeActivity extends AppCompatActivity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee);

initView();
}

private void initView() {

Button insert_button = (Button) findViewById(R.id.insert_button);
Button delete_button = (Button) findViewById(R.id.delete_button);
Button update_button = (Button) findViewById(R.id.update_button);
Button query_button = (Button) findViewById(R.id.query_button);
Button clear_button = (Button) findViewById(R.id.clear_button);
insert_button.setOnClickListener(this);
delete_button.setOnClickListener(this);
update_button.setOnClickListener(this);
query_button.setOnClickListener(this);
clear_button.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.insert_button://插入

HandleProvider.getmInstance(this).create();

break;

case R.id.delete_button:
HandleProvider.getmInstance(this).delete();
break;

case R.id.update_button:
HandleProvider.getmInstance(this).update();
break;
case R.id.query_button:
List<String> list = HandleProvider.getmInstance(this).query();
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));

}
break;
case R.id.clear_button:

break;
}

}
}


布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.ljd.client.MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
android:id="@+id/insert_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="插入" />

<Button
android:id="@+id/delete_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="删除" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
android:id="@+id/update_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="更新" />

<Button
android:id="@+id/query_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="查询" />
</LinearLayout>

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: