android ContentProvider使用

Posted 踏雪羽翼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android ContentProvider使用相关的知识,希望对你有一定的参考价值。

1、contentProvider可用于进程间的通信,即应用间数据的共享。 

2、contentProvider 的数据类型有null、Interger、real(浮点数)、text(字符串)、blob(大数据) 

3、contentProvider使用

使用首先创建一个数据库,里面可以有多个参数,具体,可自行定义 

package com.example.nsc.biglarge;

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

/**
* Created by 550211 on 2017/12/11.
* save data area size (double)
* click mode (int)
* is open (boolean)
* <p>
* NULL 空值
* INTEGER 整数
* REAL 浮点数
* TEXT 字符串
* BLOB 大数据
*/

public class DbOpenHelper extends SQLiteOpenHelper 

private static final String DATABASE_NAME = "touch_provider.db";
public static final String TOUCH_TABLE_NAME = "touch";

private static final int DB_VERSION = 1;
public static final String AREA_SIZE = "area";
public static final String CLICK_MODE = "mode";
public static final String IS_OPEN = "open";
public static final String _ID = "_id";

private String CREATE_TOUCH_TABLE = "CREATE TABLE IF NOT EXISTS " + TOUCH_TABLE_NAME +
"(_id INTEGER PRIMARY AUTOINCREMENT,area REAL,mode INTEGER,open INTEGER)";

public static final String SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TOUCH_TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ AREA_SIZE + " REAL,"
+ CLICK_MODE + " INTEGER,"
+ IS_OPEN + " INTEGER"
+ ");";

public DbOpenHelper(Context context) 
super(context, DATABASE_NAME, null, DB_VERSION);


@Override
public void onCreate(SQLiteDatabase db) 
// db.execSQL("create table touch(touchId integer primary key " + " area varchar(20),click varchar(20),open varchar(20)");
db.execSQL(SQL_CREATE_TABLE);


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
db.execSQL("DROP TABLE IF EXISTS " + TOUCH_TABLE_NAME + ";");
onCreate(db);



4、建一个类继承ContentProvider,然后在里面实现增删改除 

package com.example.nsc.biglarge;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

/**
* Created by 550211 on 2017/12/11.
*/

public class MyContentProvider extends ContentProvider 
private final String TAG = "MyContentProvider";
private DbOpenHelper mDbOpenHelper;
public static final int ITEM = 1;
public static final int ITEM_ID = 2;
private SQLiteDatabase mSqLiteDatabase;
private static final UriMatcher mMatcher = new UriMatcher(UriMatcher.NO_MATCH);

/**
* touch 表格名称
*/
static 
mMatcher.addURI("com.example.nsc.biglarge", "touch", ITEM);
//* 根据touchId来删除记录
mMatcher.addURI("com.example.nsc.biglarge", "touch/#", ITEM_ID);


@Override
public boolean onCreate() 
mDbOpenHelper = new DbOpenHelper(this.getContext());
mSqLiteDatabase = mDbOpenHelper.getReadableDatabase();
return true;


@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) 
Cursor cursor = null;
switch (mMatcher.match(uri)) 
case ITEM:
cursor = mSqLiteDatabase.query(mDbOpenHelper.TOUCH_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case ITEM_ID:
cursor = mSqLiteDatabase.query(mDbOpenHelper.TOUCH_TABLE_NAME, projection, mDbOpenHelper._ID + "=" + uri.getLastPathSegment(),
selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unknown URI" + uri);

//从而在ContentService中注册contentservice的观察者,这个观察者是cursor的内部成员(cursor是一个接口,此处真正的cursor是sqlitecursor)
//这样每个查询返回的cursor都能在contentprovider对应数据改变时得到通知,因为这些cursor都有一个成员注册成了contentservice的观察者
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;


@Override
public String getType(Uri uri) 
switch (mMatcher.match(uri)) 
case ITEM:// //数据集的MIME类型字符串则应该以vnd.android.cursor.dir/开头
return "vnd.android.cursor.dir/touch";
case ITEM_ID://单一数据的MIME类型字符串应该以vnd.android.cursor.item/开头
return "vnd.android.cursor.item/touch";
default:
throw new IllegalArgumentException("Unknown URI" + uri);



@Override
public Uri insert(Uri uri, ContentValues values) 
if (mMatcher.match(uri) != ITEM) 
throw new IllegalArgumentException("Unknown URI" + uri);

long rowId = mSqLiteDatabase.insert(mDbOpenHelper.TOUCH_TABLE_NAME, null, values);
if (rowId > 0) 
Uri noteUri = ContentUris.withAppendedId(Uri.parse("content://com.example.nsc.biglarge/" + mDbOpenHelper.TOUCH_TABLE_NAME), rowId);
getContext().getContentResolver().notifyChange(noteUri, null);
return noteUri;

throw new SQLException("Failed to insert row into " + uri);


@Override
public int delete(Uri uri, String selection, String[] selectionArgs) 
if (mMatcher.match(uri) != ITEM) 
throw new IllegalArgumentException("Unknown URI" + uri);

mSqLiteDatabase.delete(mDbOpenHelper.TOUCH_TABLE_NAME, selection, selectionArgs);
return 0;


@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) 
int count = -1;
switch (mMatcher.match(uri))

case ITEM:
count = mSqLiteDatabase.update(mDbOpenHelper.TOUCH_TABLE_NAME, values, null, null);
break;

case ITEM_ID:
String rowID = uri.getPathSegments().get(1);
count = mSqLiteDatabase.update(mDbOpenHelper.TOUCH_TABLE_NAME, values, mDbOpenHelper._ID + "=" + rowID, null);
break;
default:
throw new IllegalArgumentException("Unknow URI : " + uri);

this.getContext().getContentResolver().notifyChange(uri, null);
return count;





5、需要注册 

<provider
android:name=".MyContentProvider"
android:enabled="true"
android:authorities="com.example.nsc.biglarge"
android:exported="true" />

如果需要添加自定权限
<!--<provider-->
<!--android:name=".MyContentProvider"-->
<!--android:enabled="true"-->
<!--android:authorities="com.example.nsc.biglarge"-->
<!--android:exported="true"-->
<!--android:readPermission="com.nsc.contentProviderBlogTest.read"-->
<!--android:writePermission="com.nsc.contentProviderBlogTest.write" />-->

<!--<permission-->
<!--android:name="com.nsc.contentProviderBlogTest.read"-->
<!--android:label="provider read pomission"-->
<!--android:protectionLevel="normal" />-->
<!--<permission-->
<!--android:name="com.nsc.contentProviderBlogTest.write"-->
<!--android:label="provider write pomission"-->
<!--android:protectionLevel="normal" />-->

6、代码中写入初始数据 

private void insertData() 
ContentResolver contentResolver = getContentResolver();
contentResolver.delete(Uri.parse("content://com.example.nsc.biglarge/touch"), null, null);
ContentValues values = new ContentValues();
values.put("area", 0.5);
values.put("mode", 1);
values.put("open", 0);
contentResolver.insert(Uri.parse("content://com.example.nsc.biglarge/touch"), values);

7、实现更新数据 
private void updateData(double area, int mode, int open) 
ContentResolver contentResolver = getContentResolver();
ContentValues values = new ContentValues();
values.put("area", area);
values.put("mode", mode);
values.put("open", open);
contentResolver.update(Uri.parse("content://com.example.nsc.biglarge/touch"), values, "_id", null);

8、实现数据获取 

ContentResolver mContentResolver = getContentResolver();
Cursor cursor = mContentResolver.query(Uri.parse("content://com.example.nsc.biglarge/touch"), null, null,
null, null);
//startManagingCursor(cursor);
if (cursor!=null) 
while (cursor.moveToNext()) 
// Log.e(TAG, "area=" + cursor.getDouble(cursor.getColumnIndex("area"))
// +" mode="+cursor.getInt(cursor.getColumnIndex("mode"))
// + " open="+cursor.getInt(cursor.getColumnIndex("open")));
double area = cursor.getDouble(cursor.getColumnIndex("area"));
int mode = cursor.getInt(cursor.getColumnIndex("mode"));
int open = cursor.getInt(cursor.getColumnIndex("open"));
Log.e(TAG,"area="+area+ " mode="+mode + " open="+open);


9、 实现数据删除
contentResolver.delete(Uri.parse("content://com.example.nsc.biglarge/touch"), null, null);

10、 如果其他应用调用的话,加了自定义权限的,其他应用也要添加

<!--<uses-permission android:name="com.nsc.contentProviderBlogTest.read"/>-->
<!--<uses-permission android:name="com.nsc.contentProviderBlogTest.write"/>-->

其他应用获取数据
ContentResolver mContentResolver = getContentResolver();
Cursor cursor = mContentResolver.query(Uri.parse("content://com.example.nsc.biglarge/touch"), null, null,
null, null);
startManagingCursor(cursor);
if (cursor != null) 
while (cursor.moveToNext()) 
Log.e("nsc", "area=" + cursor.getDouble(cursor.getColumnIndex("area"))
+ " mode=" + cursor.getInt(cursor.getColumnIndex("mode"))
+ " open=" + cursor.getInt(cursor.getColumnIndex("open")));







以上是关于android ContentProvider使用的主要内容,如果未能解决你的问题,请参考以下文章

Android ContentProvider 使用

Android ContentProvider 使用

Android 总结:ContentProvider 的使用

android ContentProvider使用

Android查缺补漏--ContentProvider的使用

Android ContentProvider的介绍