• Android IPC机制之ContentProvider


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

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

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

     示例代码

    服务端:

    首先创建一个数据库

     1 package com.jiao.myaidl;
     2 
     3 import android.content.Context;
     4 import android.database.sqlite.SQLiteDatabase;
     5 import android.database.sqlite.SQLiteOpenHelper;
     6 
     7 /**
     8  * Created by jiaocg on 2016/3/12.
     9  * 数据库类
    10  */
    11 public class EmployeeDBHelper extends SQLiteOpenHelper {
    12 
    13     private final static String DB_NAME = "myDatabase.db";//数据库名字
    14     private final static int DB_VERSION = 1;
    15     public final static String EMPLOYEE_TABLE_NAME = "employee";
    16     private String CREATE_BOOK_TABLE = "CREATE TABLE IF NOT EXISTS "
    17             + EMPLOYEE_TABLE_NAME + " (id INTEGER PRIMARY KEY,"
    18             + "workNum TEXT," + "name TEXT," + "department TEXT)";
    19 
    20     public EmployeeDBHelper(Context context) {
    21         super(context, DB_NAME, null, DB_VERSION);
    22 
    23     }
    24 
    25     @Override
    26     public void onCreate(SQLiteDatabase db) {
    27 
    28         db.execSQL(CREATE_BOOK_TABLE);
    29     }
    30 
    31     @Override
    32     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    33 
    34     }
    35 }

    创建一个ContentProvider操作数据库

      1 package com.jiao.myaidl;
      2 
      3 import android.content.ContentProvider;
      4 import android.content.ContentValues;
      5 import android.content.UriMatcher;
      6 import android.database.Cursor;
      7 import android.database.sqlite.SQLiteDatabase;
      8 import android.net.Uri;
      9 import android.support.annotation.Nullable;
     10 
     11 /**
     12  * Created by jiaocg on 2016/3/12.
     13  */
     14 public class EmployeeProvider extends ContentProvider {
     15 
     16     private SQLiteDatabase mDb;
     17     private final static String AUTOORITY = "com.jiao.myaidl.employee.EmployeeProvider";
     18     private final static int EMPLOYEE_URI_CODE = 0;
     19     private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
     20 
     21 
     22     //注册uri
     23     static {
     24         sUriMatcher.addURI(AUTOORITY, "employee", EMPLOYEE_URI_CODE);
     25     }
     26 
     27 
     28     @Override
     29     public boolean onCreate() {
     30 
     31         insertDataToDb();
     32         return true;
     33     }
     34 
     35 
     36     @Nullable
     37     void insertDataToDb() {
     38 
     39         mDb = new EmployeeDBHelper(getContext()).getWritableDatabase();
     40         mDb.execSQL("delete from " + EmployeeDBHelper.EMPLOYEE_TABLE_NAME);
     41         mDb.execSQL("insert into employee values(1,'1001','张三','销售部');");
     42         mDb.execSQL("insert into employee values(2,'1002','李四','人事部');");
     43         mDb.execSQL("insert into employee values(3,'1003','王五','研发部');");
     44         mDb.execSQL("insert into employee values(4,'1004','小明','研发部');");
     45         mDb.execSQL("insert into employee values(5,'1005','小强','销售部');");
     46     }
     47 
     48 
     49     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
     50 
     51         String tableName = getTableName(uri);
     52 
     53         if (tableName == null) {
     54             throw new IllegalArgumentException("Unsupported URI: " + uri);
     55         }
     56         Cursor cursor = mDb.query(tableName, projection, selection, selectionArgs, null, null, sortOrder, null);
     57         return cursor;
     58     }
     59 
     60     @Nullable
     61     @Override
     62     public String getType(Uri uri) {
     63         return null;
     64     }
     65 
     66     @Nullable
     67     @Override
     68     public Uri insert(Uri uri, ContentValues values) {
     69         String table = getTableName(uri);
     70         if (table == null) {
     71             throw new IllegalArgumentException("Unsupported URI: " + uri);
     72         }
     73         mDb.insert(table, null, values);
     74         getContext().getContentResolver().notifyChange(uri, null);
     75         return uri;
     76     }
     77 
     78     @Override
     79     public int delete(Uri uri, String selection, String[] selectionArgs) {
     80         String table = getTableName(uri);
     81         if (table == null) {
     82             throw new IllegalArgumentException("Unsupported URI: " + uri);
     83         }
     84         int count = mDb.delete(table, selection, selectionArgs);
     85         if (count > 0) {
     86             getContext().getContentResolver().notifyChange(uri, null);
     87         }
     88         return count;
     89     }
     90 
     91     @Override
     92     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
     93         String table = getTableName(uri);
     94         if (table == null) {
     95             throw new IllegalArgumentException("Unsupported URI: " + uri);
     96         }
     97         int row = mDb.update(table, values, selection, selectionArgs);
     98         if (row > 0) {
     99             getContext().getContentResolver().notifyChange(uri, null);
    100         }
    101         return row;
    102     }
    103 
    104 
    105     private String getTableName(Uri uri) {
    106         String tableName = null;
    107         if (sUriMatcher.match(uri) == EMPLOYEE_URI_CODE) {
    108             tableName = EmployeeDBHelper.EMPLOYEE_TABLE_NAME;
    109         }
    110         return tableName;
    111     }
    112 }

    清单文件中注册ContentProvider

     

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

    客户端:

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

     1 package com.jiao.myaidl;
     2 
     3 import android.content.ContentResolver;
     4 import android.content.ContentValues;
     5 import android.content.Context;
     6 import android.database.Cursor;
     7 import android.net.Uri;
     8 import android.util.Log;
     9 import com.jiao.myaidl.entity.Employee;
    10 import java.util.ArrayList;
    11 import java.util.List;
    12 
    13 /**
    14  * Created by jiaocg on 2016/3/12.
    15  */
    16 public class HandleProvider {
    17 
    18     private static Context mContext;
    19     private static HandleProvider mInstance;
    20     private static Uri mEmployeeUri;
    21     private static final String EMPLOYEE_CONTENT_URI = "content://com.jiao.myaidl.employee.EmployeeProvider/employee";
    22 
    23     private HandleProvider(Context context) {
    24         this.mContext = context;
    25         mEmployeeUri = Uri.parse(EMPLOYEE_CONTENT_URI);
    26     }
    27 
    28 
    29     //单例
    30     public static HandleProvider getmInstance(Context context) {
    31         if (mInstance == null) {
    32             synchronized (HandleProvider.class) {
    33                 if (mInstance == null) {
    34                     mInstance = new HandleProvider(context);
    35                 }
    36             }
    37         }
    38 
    39         return mInstance;
    40     }
    41 
    42 
    43     public void delete() {
    44         ContentResolver contentResolver = mContext.getContentResolver();
    45         String where = "id=?";
    46         String[] where_args = {"7"};//满足条件的 值集合
    47         contentResolver.delete(mEmployeeUri, where, where_args);
    48     }
    49 
    50 
    51     public void update() {
    52         ContentResolver contentResolver = mContext.getContentResolver();
    53         ContentValues values = new ContentValues();
    54         values.put("name", "梁山伯");
    55         String where = "id=?";
    56         String[] where_args = {"1"};
    57         contentResolver.update(mEmployeeUri, values, where, where_args);
    58     }
    59 
    60     public void create() {
    61         ContentValues values = new ContentValues();
    62         values.put("id", 7);
    63         values.put("workNum", "1006");
    64         values.put("name", "张三丰");
    65         values.put("department", "研发部");
    66         mContext.getContentResolver().insert(mEmployeeUri, values);
    67     }
    68 
    69 
    70     public List<String> query() {
    71         List<String> list = new ArrayList<>();
    72         Cursor cursor = mContext.getContentResolver().query(mEmployeeUri, new String[]{"id", "workNum", "name", "department"}, null, null, null);
    73 
    74         while (cursor.moveToNext()) {
    75             Employee employee = new Employee();
    76             employee.setId(cursor.getInt(0));
    77             employee.setWorkNum(cursor.getString(1));
    78             employee.setName(cursor.getString(2));
    79             employee.setDepartment(cursor.getString(3));
    80             String str = employee.toString();
    81             list.add(str);
    82             Log.d("mainActivity", "query employee:" + str);
    83         }
    84         cursor.close();
    85         return list;
    86     }
    87 }

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

     1 package com.jiao.myaidl;
     2 
     3 import android.os.Bundle;
     4 import android.support.v7.app.AppCompatActivity;
     5 import android.view.View;
     6 import android.widget.Button;
     7 
     8 import com.jiao.myaidl.client.R;
     9 
    10 import java.util.List;
    11 
    12 public class EmployeeActivity extends AppCompatActivity implements View.OnClickListener {
    13 
    14     @Override
    15     protected void onCreate(Bundle savedInstanceState) {
    16         super.onCreate(savedInstanceState);
    17         setContentView(R.layout.activity_employee);
    18 
    19         initView();
    20     }
    21 
    22     private void initView() {
    23 
    24         Button insert_button = (Button) findViewById(R.id.insert_button);
    25         Button delete_button = (Button) findViewById(R.id.delete_button);
    26         Button update_button = (Button) findViewById(R.id.update_button);
    27         Button query_button = (Button) findViewById(R.id.query_button);
    28         Button clear_button = (Button) findViewById(R.id.clear_button);
    29         insert_button.setOnClickListener(this);
    30         delete_button.setOnClickListener(this);
    31         update_button.setOnClickListener(this);
    32         query_button.setOnClickListener(this);
    33         clear_button.setOnClickListener(this);
    34     }
    35 
    36     @Override
    37     public void onClick(View v) {
    38         switch (v.getId()) {
    39             case R.id.insert_button://插入
    40 
    41                 HandleProvider.getmInstance(this).create();
    42 
    43                 break;
    44 
    45             case R.id.delete_button:
    46                 HandleProvider.getmInstance(this).delete();
    47                 break;
    48 
    49             case R.id.update_button:
    50                 HandleProvider.getmInstance(this).update();
    51                 break;
    52             case R.id.query_button:
    53                 List<String> list = HandleProvider.getmInstance(this).query();
    54                 for (int i = 0; i < list.size(); i++) {
    55                     System.out.println(list.get(i));
    56 
    57                 }
    58                 break;
    59             case R.id.clear_button:
    60 
    61                 break;
    62         }
    63 
    64     }
    65 }

    布局代码:

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     xmlns:tools="http://schemas.android.com/tools"
     4     android:layout_width="match_parent"
     5     android:layout_height="match_parent"
     6     android:orientation="vertical"
     7     android:paddingBottom="@dimen/activity_vertical_margin"
     8     android:paddingLeft="@dimen/activity_horizontal_margin"
     9     android:paddingRight="@dimen/activity_horizontal_margin"
    10     android:paddingTop="@dimen/activity_vertical_margin"
    11     tools:context="com.example.ljd.client.MainActivity">
    12 
    13     <LinearLayout
    14         android:layout_width="match_parent"
    15         android:layout_height="wrap_content"
    16         android:orientation="horizontal">
    17 
    18         <Button
    19             android:id="@+id/insert_button"
    20             android:layout_width="match_parent"
    21             android:layout_height="match_parent"
    22             android:layout_weight="1"
    23             android:text="插入" />
    24 
    25         <Button
    26             android:id="@+id/delete_button"
    27             android:layout_width="match_parent"
    28             android:layout_height="match_parent"
    29             android:layout_weight="1"
    30             android:text="删除" />
    31     </LinearLayout>
    32 
    33     <LinearLayout
    34         android:layout_width="match_parent"
    35         android:layout_height="wrap_content"
    36         android:orientation="horizontal">
    37 
    38         <Button
    39             android:id="@+id/update_button"
    40             android:layout_width="match_parent"
    41             android:layout_height="wrap_content"
    42             android:layout_weight="1"
    43             android:text="更新" />
    44 
    45         <Button
    46             android:id="@+id/query_button"
    47             android:layout_width="match_parent"
    48             android:layout_height="wrap_content"
    49             android:layout_weight="1"
    50             android:text="查询" />
    51     </LinearLayout>
    52 
    53 </LinearLayout>
  • 相关阅读:
    [小技巧]记录PHP错误日志
    PHP __autoload函数(自动载入类文件)的使用方法
    php5.3以前的版本安装出现Fatal error: Call to undefined function mysql_connect()
    mysqlnoinstall5.1.62win32 安装
    [php]PHP错误处理
    哈希表1
    哈希表2
    WinSock編程的多線程式控制
    编码转换 unicode gbk big5
    Parameters转换为Variant数组
  • 原文地址:https://www.cnblogs.com/all88/p/5274885.html
Copyright © 2020-2023  润新知