该系统有两个应用,比较繁琐。但是内容提供者是android里非常非常重要的一个内容,我们得好好学习下哦。先看效果图,我们提供了四个按钮,点击按钮便会进行相应的操作。
我们先看内容提供者所在的应用,代码结构:
activity代码:
- package cn.com.contentProvider;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.TextView;
-
- public class ContentProviderAcitivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- }
- }
MyContentProvider.java代码
- package cn.com.contentProvider;
-
- import android.content.ContentProvider;
- import android.content.ContentUris;
- import android.content.ContentValues;
- import android.content.Context;
- import android.content.UriMatcher;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.net.Uri;
-
- public class MyContentProvider extends ContentProvider {
-
- private MyOpenHelper myOpenHelper;
-
-
- private SQLiteDatabase sqLiteDatabase;
-
-
- private static UriMatcher uriMatcher;
-
-
- private static final String authority = "cn.com.chenzheng_java.hello";
-
-
- static {
- uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
-
- uriMatcher.addURI(authority, "path_chenzheng", 1);
- uriMatcher.addURI(authority, "path_chenzheng/#", 2);
- }
-
-
- private static final String _id = "id";
- private static final String name = "name";
- private static final String age = "age";
- private static final String isMan = "isMan";
-
-
- @Override
- public boolean onCreate() {
- try {
- myOpenHelper = new MyOpenHelper(getContext(), DB_Name, null,
- Version_1);
-
- } catch (Exception e) {
-
- return false;
- }
- return true;
- }
-
-
- @Override
- public int delete(Uri uri, String selection, String[] selectionArgs) {
- int number = 0;
- sqLiteDatabase = myOpenHelper.getWritableDatabase();
- int code = uriMatcher.match(uri);
- switch (code) {
- case 1:
- number = sqLiteDatabase
- .delete(Table_Name, selection, selectionArgs);
- break;
- case 2:
- long id = ContentUris.parseId(uri);
-
- selection = (selection == null || "".equals(selection.trim())) ? _id
- + "=" + id
- : selection + " and " + _id + "=" + id;
- number = sqLiteDatabase
- .delete(Table_Name, selection, selectionArgs);
- break;
- default:
- throw new IllegalArgumentException("异常参数");
- }
-
- return number;
- }
-
-
- @Override
- public String getType(Uri uri) {
- int code = uriMatcher.match(uri);
- switch (code) {
- case 1:
- return "vnd.android.cursor.dir/chenzheng_java";
- case 2:
- return "vnd.android.cursor.item/chenzheng_java";
- default:
- throw new IllegalArgumentException("异常参数");
- }
-
- }
-
-
- @Override
- public Uri insert(Uri uri, ContentValues values) {
- sqLiteDatabase = myOpenHelper.getWritableDatabase();
- int code = uriMatcher.match(uri);
- switch (code) {
- case 1:
- sqLiteDatabase.insert(Table_Name, name, values);
- break;
- case 2:
- long id = sqLiteDatabase.insert(Table_Name, name, values);
-
- ContentUris.withAppendedId(uri, id);
- break;
- default:
- throw new IllegalArgumentException("异常参数");
- }
-
- return uri;
- }
-
-
- @Override
- public Cursor query(Uri uri, String[] projection, String selection,
- String[] selectionArgs, String sortOrder) {
- Cursor cursor = null;
- sqLiteDatabase = myOpenHelper.getReadableDatabase();
- int code = uriMatcher.match(uri);
- switch (code) {
- case 1:
- cursor = sqLiteDatabase.query(Table_Name, projection, selection,
- selectionArgs, null, null, sortOrder);
- break;
- case 2:
-
- long id = ContentUris.parseId(uri);
- selection = (selection == null || "".equals(selection.trim())) ? _id
- + "=" + id
- : selection + " and " + _id + "=" + id;
- cursor = sqLiteDatabase.query(Table_Name, projection, selection,
- selectionArgs, null, null, sortOrder);
- break;
- default:
- throw new IllegalArgumentException("参数错误");
- }
-
- return cursor;
- }
-
-
- @Override
- public int update(Uri uri, ContentValues values, String selection,
- String[] selectionArgs) {
- int num = 0;
- sqLiteDatabase = myOpenHelper.getWritableDatabase();
- int code = uriMatcher.match(uri);
- switch (code) {
- case 1:
- num = sqLiteDatabase.update(Table_Name, values, selection, selectionArgs);
- break;
- case 2:
- long id = ContentUris.parseId(uri);
- selection = (selection == null || "".equals(selection.trim())) ? _id
- + "=" + id
- : selection + " and " + _id + "=" + id;
- num = sqLiteDatabase.update(Table_Name, values, selection, selectionArgs);
- break;
- default:
- break;
- }
- return num;
- }
-
-
- private final String DB_Name = "chenzheng_java.db";
-
- private final String Table_Name = "chenzheng_java";
-
- private final int Version_1 = 1;
-
- private class MyOpenHelper extends SQLiteOpenHelper {
-
- public MyOpenHelper(Context context, String name,
- CursorFactory factory, int version) {
- super(context, name, factory, version);
- }
-
-
- @Override
- public void onCreate(SQLiteDatabase db) {
- String sql = " create table if not exists " + Table_Name
- + "(id INTEGER,name varchar(20),age integer,isMan boolean)";
- db.execSQL(sql);
- }
-
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- String sql = " drop table if exists " + Table_Name;
- db.execSQL(sql);
- onCreate(db);
- }
-
- }
- }
androidManifest.xml代码
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="cn.com.contentProvider" android:versionCode="1"
- android:versionName="1.0">
- <uses-sdk android:minSdkVersion="8" />
-
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".ContentProviderAcitivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <provider android:name=".MyContentProvider"
- android:authorities="cn.com.chenzheng_java.hello"
- android:multiprocess="true" android:permission="cn.com.chenzheng_java.permission"></provider>
- </application>
- <!--
- permission中的android:name的值与provider中的android:permission的值是一样的
- android:protectionLevel 则代表了权限等级
- -->
- <permission android:name="cn.com.chenzheng_java.permission"
- android:protectionLevel="normal"></permission>
-
- </manifest>
main.xml为默认。
----------------------------------------------------------------------------------------------------------------
第二个应用(用于访问内容提供者的应用)
activity代码
- package cn.com.chenzheng_java;
-
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- public class ContentAccessActivity extends Activity {
- private final static String tag = "通知";
- private TextView textView;
- String result = "结果:/n";
- ContentResolver reslover;
- Uri uri;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- uri = Uri.parse("content://cn.com.chenzheng_java.hello/path_chenzheng");
-
-
- reslover = this.getContentResolver();
- textView = (TextView) findViewById(R.id.textView);
-
- Button insertButton = (Button) findViewById(R.id.insertButton);
- insertButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- insert(reslover, uri);
- }
- });
-
- Button deleteButton = (Button) findViewById(R.id.deleteButton);
- deleteButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- delete(reslover, uri);
- }
- });
-
- Button updateButton = (Button) findViewById(R.id.updateButton);
- updateButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- update(reslover, uri);
- }
- });
-
- Button queryButton = (Button) findViewById(R.id.queryButton);
- queryButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- query(reslover, uri);
- }
- });
-
- }
-
- private void insert(ContentResolver resolver, Uri uri) {
- ContentValues contentValues = new ContentValues();
- contentValues.put("name", "张小凡");
- contentValues.put("age", 22);
- contentValues.put("isMan", true);
- Uri uri2 = resolver.insert(uri, contentValues);
- Log.i(tag, "插入成功!");
- result += "成功插入了一条记录,uri为" + uri2;
- textView.setText(result);
- result = "";
- }
-
- private void update(ContentResolver resolver, Uri uri) {
- ContentValues contentValues = new ContentValues();
- contentValues.put("age", 122);
- int number = resolver.update(uri, contentValues, null, null);
- Log.i(tag, "更新成功!");
- result += "成功更新了" + number+"条记录";
- textView.setText(result);
- result = "";
-
- }
- private void delete(ContentResolver resolver, Uri uri) {
- String where = " 1=1 and isMan=?";
-
- String[] selectionArgs = new String[] { "1" };
- int number = resolver.delete(uri, where, selectionArgs);
- Log.i(tag, "删除成功!");
- textView.setText(result + "成功删除了" + number + "条记录");
- result = "";
- }
-
- private void query(ContentResolver resolver, Uri uri) {
-
- String[] projection = new String[] { "id", "name", "age", "isMan" };
- Cursor cursor = resolver.query(uri, projection, null, null, null);
- int count = cursor.getCount();
- Log.i(tag, "总记录数" + count);
-
- int idIndex = cursor.getColumnIndex("id");
- int nameIndex = cursor.getColumnIndex("name");
- int ageIndex = cursor.getColumnIndex("age");
- int isManIndex = cursor.getColumnIndex("isMan");
-
- cursor.moveToFirst();
- while (!cursor.isAfterLast()) {
- int id = cursor.getInt(idIndex);
- String name = cursor.getString(nameIndex);
- int age = cursor.getInt(ageIndex);
- int isMan = cursor.getInt(isManIndex);
- Log.i(tag, "id=" + id + " name=" + name + " age=" + age + " isMan="
- + isMan);
- result += "id=" + id + " name=" + name + " age=" + age + " isMan="
- + isMan;
- cursor.moveToNext();
- }
-
- textView.setText(result);
- result = "";
-
- }
-
- }
manifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="cn.com.chenzheng_java"
- android:versionCode="1"
- android:versionName="1.0">
- <uses-sdk android:minSdkVersion="8" />
-
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".ContentAccessActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- </application>
-
- <uses-permission android:name="cn.com.chenzheng_java.permission"></uses-permission>
- </manifest>
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/textView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Button
- android:id="@+id/insertButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="insert"
- ></Button>
- <Button
- android:id="@+id/deleteButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="delete"
- ></Button>
- <Button
- android:id="@+id/updateButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="update"
- ></Button>
- <Button
- android:id="@+id/queryButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="query"
- ></Button>
- </LinearLayout>
--------------------------------------------------------------------------------
想说的话,在代码的注释中已经说的很清晰了。这里再次重复下我们定义和使用内容提供者的步骤吧。
定义内容提供者:
我们定义内容提供者的目的是什么,共享数据,对,定义内容提供者的目的就是让别的应用能够访问当前应用的一些数据,至于到底暴露给外界什么数据,我们可以 在定义内容提供者的时候详细控制!不管如何,我们明确了第一个问题,定义内容提供者的目的----数据共享!
我们平时对数据的操作都有哪些?增删改查!就四个字!这也是为什么我们再定义内容提供者的时候必须要实现相应的方法了。当然如果你要是不想提供相应的操作,你可以在内部进行方法空实现。
是不是所有的应用都可以访问我啊?不可能!我们可不是随便的人,对吧!所以我们要进行验证,验证不通过的直接让它去死就可以了。验证怎么验证啊?通过UriMatcher进行匹配!
现在我们已经提供了访问接口了,我们怎么让系统知道,别的应用可以用我的东西啊?去配置文件中注册!!
使用内容提供者:
如何找到该内容提供者啊?需要Uri和相应的访问权限。相当于地址
如何进行增删查改啊?通过ContentResolver对象的相应方法。