android基础—->ContentProvider的使用
內容出示器(Content Provider)关键用以在不一样的应用软件中间完成信息共享的作用,它出示了一套详细的体制,容许一个程序流程浏览另一个程序流程中的数据信息,另外还能确保被访数据信息的安全系数。现阶段,应用內容出示器是Android 完成跨程序流程共享资源数据信息的规范方法。有别于文档存储和SharedPreferences 储存中的二种全局性可存取数据方式,內容出示器能够挑选只对哪一部分数据信息开展共享资源,进而确保大家程序流程中的隐私保护数据信息不容易有泄露的风险性。下面,大家逐渐內容出示器的学习培训。content provider的基本原理表明,参照此外一篇blog(android高級—->ContentProvider的源代码剖析)
文件目录导航栏:
- 內容出示器简易表明
- 浏览其他的Content Provider
- 建立自身的Content Provider
- 友链
內容出示器简易表明
一、 內容出示器的使用方法:
- 应用目前的內容出示器来载入和实际操作相对程序流程中的数据信息
- 建立自身的內容出示器给大家程序流程的数据信息出示外界浏览插口,必须承继ContentProvider类
二、 ContentResolver的基础使用方法:
- 获得案例: 能够根据Context 中的getContentResolver()方式获得到此类的案例
- 基础方式: 出示了一系列的方式用以对数据信息开展CRUD 实际操作
- 应用留意: ContentResolver中的增删方式全是不接受表名主要参数的,只是应用一个Uri 主要参数替代,这一主要参数被称作Content URI。
三、 內容URI的基础详细介绍:
- 关键作为: 內容URI 给內容出示器中的数据信息创建了唯一标志符
- 构成部分: 管理权限(authority)和途径(path)。
- 管理权限途径: 管理权限是用以对不一样的应用软件做区别的,一般为了更好地防止矛盾,都是会选用软件包名的方法来开展取名;途径则是用以对同一应用软件中不一样的表做区别的,一般 都是会加上到管理权限的后边。
浏览其他的Content Provider
建立一个简易新项目,构造以下:
一、 在activity_main.xml文件中建立一个ListView的合理布局:
<LinearLayout xmlns:android="http://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; } }
二、 然后创建一个有关数据库查询的java工具: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(0
//回到数据信息的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