今天一天就弄懂了这个原理。一定要注意uri对应方法。uri表达当时不清楚的可以百度看看哈
创建ContentProvider的步骤:
1、该子类继承ContentProvider,并实现增删改查方法2、AndroidManifest.xml文件中注册该ContentProvider
开发ContentProvider实现的增删改查都需要Uri参数,Android提供了UriMatcher工具类
例子:将上次开发保存生词的应用编程实现数据共享
1、定义一个WrodsUtil类,用来存放ContentProvider访问的常用入口
2、定义DictProvider类继承ContentProvider并重写增删改查方法
3、在Manifest中注册ContentProvider
-------在另外一个应用程序中使用此ContentProvider暴漏的数据
1、创建ContentResolver类,
2、调用提供的增删改查方法。传入uri路径即可
WordsUtil.java该类提供了静态的常用属性。方便调用和使用。
package lzl.edu.com.savewords;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Created by admin on 2015/9/29.
*/
public final class WordsUtil {
/**
* 该类主要用于提供 ContentProvider访问的常用入口
*/
public static final String AUTHORITY = "lzl.edu.com.savewords";
public static final class words implements BaseColumns{
//定义Content允许操作的三个数据列
public static final String _ID = "_id";
public static final String WORD = "word";
public static final String EXPALAIN = "explain";
//定义content提供服务的两个uri
public static final Uri DICT_CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/words");
public static final Uri WORD_CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/word");
}
}
DictProvider.java 该类继承ContentProvider类,实现了增删改查的方法
package lzl.edu.com.savewords;
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;
import android.util.Log;
/**
* Created by admin on 2015/9/29.
*/
public class DictProvider extends ContentProvider {
//创建工作
public static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
public static final int WORDS = 1;
public static final int WORD = 2;
private MySQLHelper sqlHelper;
static {
//在UriMather中注册Uri
matcher.addURI(WordsUtil.AUTHORITY,"words",WORDS );
matcher.addURI(WordsUtil.AUTHORITY,"word/#",WORD);
}
@Override
public boolean onCreate() {
//初始化DictProvider时,创建MySQLHelper对象
sqlHelper = new MySQLHelper(this.getContext(),"mysql.db",1);
Log.i("onCreate:","----------");
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = sqlHelper.getReadableDatabase();
switch (matcher.match(uri)){
case WORDS:
return db.query("mywords",projection,selection,selectionArgs,null,null,sortOrder);
case WORD:
//解析出要删除的记录
long id = ContentUris.parseId(uri);
String where = WordsUtil.words._ID+"="+id;
if(selection!=null&&!selection.equals("")){
where = where +"and"+ selection;
}
return db.query("mywords", projection, where, selectionArgs, null, null, sortOrder);
default:
throw new IllegalArgumentException("未知uri:"+uri);
}
}
//返回指定uri参数对应的数据MIME类型
/**
* 这里主要说下Url所代表数据的MIME类型:
如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头,
例如:要得到所有mywords记录的Uri为content://lzl.edu.com.savewords/mywords,那么返回的MIME类型字符串应该为:"vnd.android.cursor.dir/mywords"。
如果要操作的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头,
例如:得到id为1234的person记录,Uri为content://lzl.edu.com.savewords/mywords/1234,那么返回的MIME类型字符串为:"vnd.android.cursor.item/mywords"。
* @param uri
* @return
*/
@Override
public String getType(Uri uri) {
switch (matcher.match(uri)){
//操作多项记录
case WORDS:
return "vnd.android.cursor.dir/words";
//操作单项记录
case WORD:
return "vnd.android.cursor.item/word";
default:
throw new IllegalArgumentException("未知uri:"+uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
//获得SQLiteDatabase实例
SQLiteDatabase db = sqlHelper.getReadableDatabase();
//插入数据,返回rowId
long rowId = db.insert("mywords",WordsUtil.words._ID,values);
Log.i("id----",rowId+"");
//如果插入成功,则返回Uri
if(rowId>0){
Uri wordsUri = ContentUris.withAppendedId(uri,rowId);
//通知数据已经改变
getContext().getContentResolver().notifyChange(uri,null);
return wordsUri;
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int num=0;
SQLiteDatabase db = sqlHelper.getWritableDatabase();
switch (matcher.match(uri)){
case WORD:
num = db.delete("mywords",selection,selectionArgs);
break;
case WORDS:
//解析出要删除的记录
long id = ContentUris.parseId(uri);
String where = WordsUtil.words._ID+"="+id;
if(selection!=null&&!selection.equals("")){
where = where +"and"+ selection;
}
num = db.delete("mywords",where,selectionArgs);
break;
default:
throw new IllegalArgumentException("未知uri:"+uri);
}
//通知数据已经改变
getContext().getContentResolver().notifyChange(uri,null);
return num;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int num;
SQLiteDatabase db = sqlHelper.getWritableDatabase();
Log.i("matcher.match(uri)",matcher.match(uri)+"");
switch (matcher.match(uri)){
case WORDS:
num = db.update("mywords",values,selection,selectionArgs);
break;
case WORD:
//解析出要删除的记录
long id = ContentUris.parseId(uri);
String where = WordsUtil.words._ID+"="+id;
if(selection!=null&&!selection.equals("")){
where = where +"and"+ selection;
}
num = db.update("mywords", values, where, selectionArgs);
break;
default:
throw new IllegalArgumentException("未知uri:"+uri);
}
getContext().getContentResolver().notifyChange(uri,null);
return num;
}
}
在AndroidManifest.xml中注册provider
<!--注册一个ContentProvider-->
<provider
android:name=".DictProvider"
android:authorities="lzl.edu.com.savewords"
android:exported="true"
/>
在另外一个应用程序中,便可以调用该应用程序的数据了。注意这里使用的WordUtil类。
MainActivity.java
package lzl.edu.com.contentresolvertest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity implements View.OnClickListener {
EditText mEWord, mEMean, mESearch;
Button mBSave, mBSearch;
private ContentResolver resolver;
Uri uri = Uri.parse("content://lzl.edu.com.savewords.DicProvider/mywords");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resolver = getContentResolver();
//创建数据库对象
mEWord = (EditText) findViewById(R.id.myword_edit);
mEMean = (EditText) findViewById(R.id.mymean_edit);
mESearch = (EditText) findViewById(R.id.mysearch_edit);
mBSave = (Button) findViewById(R.id.save_btn);
mBSearch = (Button) findViewById(R.id.select_btn);
mBSearch.setOnClickListener(this);
mBSave.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.save_btn://插入语句
String word = mEWord.getText().toString();
String mean = mEMean.getText().toString();
ContentValues values = new ContentValues();
values.put(WordsUtil.words.WORD,word);
values.put(WordsUtil.words.EXPALAIN,mean);
Uri id= resolver.insert(WordsUtil.words.DICT_CONTENT_URI,values);
if(id!=null){
Toast.makeText(this, "保存成功!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"保存失败!",Toast.LENGTH_LONG).show();
}
break;
case R.id.select_btn:
String key = mESearch.getText().toString();
//调用查询语句,返回Cursor类的对象
Cursor cursor = resolver.query(WordsUtil.words.DICT_CONTENT_URI,
null,"word like ? or explain like ?",
new String[]{"%"+key+"%","%"+key+"%"},null);
//将Cursor类的数据封装成ArrayList集合。并放到另一个Activity中显示
Intent intent = new Intent(MainActivity.this,DialogActivity.class);
intent.putExtra("data",CursorList(cursor));
startActivity(intent);
break;
}
}
//将获取的cursor存到List集合中
public ArrayList<Map<String, String>> CursorList(Cursor cursor) {
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
//遍历游标,将数据存储到list集合中
while (cursor.moveToNext()) {
Map<String, String> list_item = new HashMap<String, String>();
list_item.put("word", cursor.getString(1));
list_item.put("explain", cursor.getString(2));
list.add(list_item);
}
return list;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}