项目一:自定义内容提供者
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sg31.sgcontentprovider"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
// 单元测试 注意 targetPackage!!!!!!!!!!!
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.sg31.sgcontentprovider"
></instrumentation>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
// 单元测试
<uses-library android:name="android.test.runner"/>
<activity
android:name=".MainActivity"
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=".UserProvider"
android:authorities="com.sg31.contentprovider"
android:exported="true"
></provider>
</application>
</manifest>
自定义内容提供者:
package com.sg31.sgcontentprovider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class UserProvider extends ContentProvider {
private SGOpenHelper oh;
SQLiteDatabase db;
// 创建uri匹配器对象
static UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH);
// 检测其他用户传入的uri与匹配器定义好的uri中,哪条匹配
static {
um.addURI("com.sg31.contentprovider", "usertable", 1);// content://com.sg31.contentprovide/usertable
um.addURI("com.sg31.contentprovider", "girltable", 2);// content://com.sg31.contentprovide/girltable
um.addURI("com.sg31.contentprovider", "usertable/#", 3);// content://com.sg31.contentprovide/usertable/4
}
// 内容提供者创建时调用
@Override
public boolean onCreate() {
oh = new SGOpenHelper(getContext());
db = oh.getWritableDatabase();
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Cursor cursor = null;
if (um.match(uri) == 1) {
cursor = db.query("usertable", projection, selection, selectionArgs,
null, null, sortOrder, null);
} else if (um.match(uri) == 2) {
cursor = db.query("girltable", projection, selection, selectionArgs,
null, null, sortOrder, null);
} else if (um.match(uri) == 3) {
// 把uri末尾携带的数字取出来
long id = ContentUris.parseId(uri);
cursor = db.query("usertable", projection, "_id = ?",
new String[] { id + "" }, null, null, sortOrder, null);
} else {
throw new IllegalArgumentException("uri又有问题哟亲么么哒");
}
return cursor;
}
@Override
public String getType(Uri uri) {
if (um.match(uri) == 1) {
return "vnd.android.cursor.dir/usertable";
} else if (um.match(uri) == 3) {
return "vnd.android.cursor.item/usertable";
}
return null;
}
// 此方法供其他应用调用,用于往people数据库里插数据
// values:由其他应用传入,用于封装要插入的数据
// uri:内容提供者的主机名,也就是地址
@Override
public Uri insert(Uri uri, ContentValues values) {
// 使用uri匹配器匹配传入的uri
if (um.match(uri) == 1) {
db.insert("usertable", null, values);
// 发送数据改变的通知
// uri:通知发送到哪一个uri上,所有注册在这个uri上的内容观察者都可以收到这个通知
getContext().getContentResolver().notifyChange(uri, null);
} else if (um.match(uri) == 2) {
db.insert("girltable", null, values);
getContext().getContentResolver().notifyChange(uri, null);
} else {
throw new IllegalArgumentException("uri有问题哟亲么么哒");
}
return uri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// 本来还要根据uri来判断的,但是这儿暂时直接写死
int i = db.delete("usertable", selection, selectionArgs);
return i;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int i = db.update("usertable", values, selection, selectionArgs);
return i;
}
}
数据库操作类:
package com.sg31.sgcontentprovider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SGOpenHelper extends SQLiteOpenHelper {
public SGOpenHelper(Context context) {
super(context, "userdata.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table usertable(_id integer primary key autoincrement, name char(10), money integer(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("create table girltable(_id integer primary key autoincrement, name char(10))");
}
}
测试类:
package com.sg31.sgcontentprovider;
import android.test.AndroidTestCase;
public class SGTestCase extends AndroidTestCase {
// 测计,必须是public的方法!!!
public void testAdd() {
// 断言
SGOpenHelper oh = new SGOpenHelper(getContext());
oh.getWritableDatabase();
}
}
项目二:访问内容提供者
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.sg31.accesscontentprovider.MainActivity"
android:orientation="vertical"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="插入"
android:onClick="insertBtnClicked"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删除"
android:onClick="deleteBtnClicked"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改"
android:onClick="updateBtnClicked"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查询"
android:onClick="selectBtnClicked"
/>
</LinearLayout>
控制器:
package com.sg31.accesscontentprovider;
import android.support.v7.app.ActionBarActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void insertBtnClicked(View v){
//通过内容提供者把数据插入另一个app的user数据库
//拿到contentResolver
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "beyond");
// values.put("money", "5267");
//url:内容提供者的主机名
//values:要插入的数据
cr.insert(Uri.parse("content://com.sg31.contentprovider/usertable"), values);
}
public void deleteBtnClicked(View v){
ContentResolver cr = getContentResolver();
int i = cr.delete(Uri.parse("content://com.sg31.contentprovider"), "name = ?", new String[]{"beyond"});
System.out.println(i);
}
public void updateBtnClicked(View v){
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "dnoyeb");
int i = cr.update(Uri.parse("content://com.sg31.contentprovider"), values, "name = ?", new String[]{"beyond"});
System.out.println(i);
}
public void selectBtnClicked(View v){
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.sg31.contentprovider/usertable/4"), null, null, null, null);
while(cursor.moveToNext()){
String name = cursor.getString(1);
String money = cursor.getString(2);
System.out.println(name + ";" + money);
}
}
}