Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 基礎—ContentProvider 內容提供器的使用

編輯:Android 程式設計入門

內容提供器(Content Provider)主要用於在不同應用程式之間實現資料共享。它提供了一整套機制,讓一個程式能安全地存取另一個程式中的資料。目前,使用內容提供器是 Android 實現跨程式共享資料的標準方式。有別於檔案儲存與 SharedPreferences 那種全局可讀寫的模式,內容提供器可以選擇只共享特定部分的資料,藉此保障程式的隱私資料不會外洩。關於 ContentProvider 的原理說明,可參考另一篇探討其原始碼分析的文章。

 

 目錄導航:

  1.   內容提供器簡單說明
  2.   訪問其它的 Content Provider
  3.   創建自己的 Content Provider
  4.   友情鏈接

 

內容提供器簡單說明

一、內容提供器的用法:

  • 使用現有的內容提供器來讀取和操作對應程式中的資料
  • 創建自己的內容提供器,為程式的資料提供外部存取介面,需繼承 ContentProvider 類

二、ContentResolver 的基本用法:

  • 取得實例:可透過 Context 的 getContentResolver() 方法取得該類的實例
  • 基本方法:提供了一系列方法用於對資料進行 CRUD 操作
  • 使用注意:ContentResolver 的增刪改查方法都不接收表名參數,而是用一個名為 Content URI 的 Uri 參數來代替

三、內容 URI 的基本介紹:

  • 重要用途:內容 URI 為內容提供器中的資料建立唯一標識符
  • 組成部分:權限(authority)和路徑(path)
  • 權限與路徑:權限用來區分不同應用程式,為避免衝突,通常採用程式包名的方式命名;路徑則用來區分同一應用程式中不同的表,通常接在權限後面

 

訪問其它的 Content Provider

建立一個簡單專案,結構如下:

 

一、在 activity_main.xml 中建立一個 ListView 布局:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>

 

二、在 MainActivity.java 中:

package com.example.linux.getcontact; import android.database.Cursor; import android.os.Bundle; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView listView; ArrayAdapter<String> adapter; List<String> contactsList = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, contactsList); listView.setAdapter(adapter); readContacts(); } private void readContacts() { Cursor cursor = null; try { // 查詢聯系人數據 cursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { // 獲取聯系人姓名 String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); // 獲取聯系人手機號 String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); contactsList.add(displayName + "\n" + number); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } } }

 

三、讀取系統聯絡人是需要聲明權限的,在 AndroidManifest.xml 中加上:

 <uses-permission android:name="android.permission.READ_CONTACTS" />

 

創建自己的 Content Provider

在程式中存取其他應用程式的資料,整體思路其實很簡單:只要取得對方的內容 URI,再借助 ContentResolver 進行 CRUD 操作即可。以下我們來建立自己的內容提供器。

創建內容提供器—Server

專案結構:

 

一、建立一個與資料庫表對應的 Bean:Person.java:

package com.example.linux.contentproviderserver.model; /** * Created by Linux on 2016/3/4. */ public class Person { private Integer _id; private String name; private String age; public Integer get_id() { return _id; } public void set_id(Integer _id) { this._id = _id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }

 

二、接著建立一個資料庫工具類:DBOpenHelper.java

package com.example.linux.contentproviderserver.util; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Linux on 2016/3/4. */ public class DBOpenHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "person.db"; //數據庫名稱 private static final int DATABASE_VERSION = 1;//數據庫版本 private static final String CREATE_TABLE_PERSON = "CREATE TABLE person (_id integer primary key autoincrement, name varchar(20), age varchar(10))"; private static final String DROP_TABLE_PERSON = "DROP TABLE IF EXISTS person"; public DBOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_PERSON); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DROP_TABLE_PERSON); onCreate(db); } }

 

三、建立一個繼承 ContentProvider 的內容提供器:PersonProvider.java

  • 先做一些初始化工作:
private final static String TAG = "PersonProvider"; 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; private static final String AUTHORITY = "com.example.linux.contentproviderserver.action.PersonProvider"; private static final String PATH_1 = "person"; private static final String PATH_2 = "person/#"; static { Log.i(TAG, "on PersonProvider static"); MATCHER.addURI(AUTHORITY, PATH_1, PERSONS); MATCHER.addURI(AUTHORITY, PATH_2, PERSON); } @Override public boolean onCreate() { Log.i(TAG, "on PersonProvider create"); this.dbOpenHelper = new DBOpenHelper(this.getContext()); return false; }
  • 重寫插入方法 insert():
// 插入person表中的所有記錄 /person // 插入person表中指定id的記錄 /person/10 @Override public Uri insert(Uri uri, ContentValues values) { Log.i(TAG, "uri: " + uri.getPath() + ", values: " + values.getAsString("name")); SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); switch (MATCHER.match(uri)) { case PERSONS: // 特別說一下第二個參數是當name字段為空時,將自動插入一個NULL。 long rowid = db.insert("person", "name", values); Uri insertUri = ContentUris.withAppendedId(uri, rowid);// 得到代表新增記錄的Uri this.getContext().getContentResolver().notifyChange(uri, null); return insertUri; case PERSON: Log.i("some", "soem"); return null; default: throw new IllegalArgumentException("Unkwon Uri:" + uri.toString()); } }
  • 重寫刪除方法 delete():
@Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int count = 0; switch (MATCHER.match(uri)) { case PERSONS: count = db.delete("person", selection, selectionArgs); return count; case PERSON: long id = ContentUris.parseId(uri); String where = "_id=" + id; if (selection != null && !"".equals(selection)) { where = selection + " and " + where; } count = db.delete("person", where, selectionArgs); return count; default: throw new IllegalArgumentException("Unkwon Uri:" + uri.toString()); } }
  • 重寫更新方法 update():
@Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int count = 0; switch (MATCHER.match(uri)) { case PERSONS: count = db.update("person", values, selection, selectionArgs); return count; case PERSON: long id = ContentUris.parseId(uri); String where = "_id=" + id; if (selection != null && !"".equals(selection)) { where = selection + " and " + where; } count = db.update("person", values, where, selectionArgs); return count; default: throw new IllegalArgumentException("Unkwon Uri:" + uri.toString()); } }
  • 重寫查詢方法 query():
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Log.i(TAG, "PersonProvider query"); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); int matchResult = MATCHER.match(uri); switch (MATCHER.match(uri)) { case PERSONS: return db.query("person", projection, selection, selectionArgs, null, null, sortOrder); case PERSON: long id = ContentUris.parseId(uri); String where = "_id=" + id; if (selection != null && !"".equals(selection)) { where = selection + " and " + where; } return db.query("person", projection, where, selectionArgs, null, null, sortOrder); default: throw new IllegalArgumentException("Unkwon Uri:" + uri.toString()); } }
  • 重寫類型方法 getType():
//返回數據的MIME類型。 @Override public String getType(Uri uri) { Log.i(TAG, "PersonProvider get type"); switch (MATCHER.match(uri)) { case PERSONS: return "vnd.android.cursor.dir/person"; case PERSON: return "vnd.android.cursor.item/person"; default: throw new IllegalArgumentException("Unkwon Uri:" + uri.toString()); } }

 

 五、在 MainActivity 中,為了方便取得資料庫中的資料,加入了查詢與新增方法:

package com.example.linux.contentproviderserver; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Toast; import com.example.linux.contentproviderserver.util.DBOpenHelper; /** * writer: huhx * 內容提供器的服務端 */ public class MainActivity extends AppCompatActivity { private final static String TAG = "PersonProvider"; private DBOpenHelper dbOpenHelper; SQLiteDatabase database = null; private StringBuffer stringBuffer = null; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "main on create."); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbOpenHelper = new DBOpenHelper(this); database = dbOpenHelper.getWritableDatabase(); } // 查詢所有的數據 public void queryAll(View view) { stringBuffer = new StringBuffer(); Cursor cursor = database.rawQuery("select * from person", null); cursor.moveToFirst(); while(cursor.moveToNext()) { String name = cursor.getString(1); int age = cursor.getInt(2); stringBuffer.append("name: " + name + ", age: " + age + "\n"); } if (stringBuffer.toString().equals("")) { Toast.makeText(MainActivity.this, "nothing", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, stringBuffer, Toast.LENGTH_SHORT).show(); } } //插入數據 public void insertData(View view) { Object[] object = new Object[]{"linux", 23}; database.execSQL("insert into person(name, age) values(?, ?)", object); } @Override protected void onDestroy() { super.onDestroy(); database.close(); } }

 

使用內容提供器—Client

專案結構:

一、在 MainActivity 中加上查詢與插入功能:

package com.example.linux.contentproviderclient; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; /** * 內容提供器的客戶端 */ public class MainActivity extends AppCompatActivity { private StringBuffer stringBuffer = new StringBuffer(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // 插入數據 public void insert(View view) { ContentResolver contentResolver = getContentResolver(); Uri insertUri = Uri.parse("content://com.example.linux.contentproviderserver.action.PersonProvider/person"); ContentValues values = new ContentValues(); values.put("name", "wangkuifeng"); values.put("age", 23); Uri uri = contentResolver.insert(insertUri, values); Toast.makeText(MainActivity.this, "insert success: " + uri, Toast.LENGTH_SHORT).show(); } // 查詢數據 public void query(View view) { ContentResolver contentResolver = getContentResolver(); Uri queryUri = Uri.parse("content://com.example.linux.contentproviderserver.action.PersonProvider/person/5"); Cursor queryResult = contentResolver.query(queryUri, null, null, null, null); int count = queryResult.getCount(); for (queryResult.moveToFirst(); !queryResult.isAfterLast(); queryResult.moveToNext()) { String name = queryResult.getString(1); int age = queryResult.getInt(2); stringBuffer.append("name: " + name + ", age: " + age + "\n"); } Toast.makeText(MainActivity.this, stringBuffer.toString() + "\ncount: " + count, Toast.LENGTH_SHORT).show(); queryResult.close(); } }

 

友情鏈接

  • 訪問其它的 Content Provider   訪問密碼 777a
  • 創建自己的 Content Provider   訪問密碼 7388
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved