<span style="white-space:pre"> <span style="white-space:pre"> </span>------<a target=_blank target="_blank" href="http://www.itheima.com">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! ------- </span>
<span style="white-space:pre">
</span>
<span style="white-space:pre">
</span>
</pre><pre name="code" class="html"><span style="white-space:pre"> </span>Android 中的数据库是对应用私有的,自己是无法使用别的应用的数据库的。但是往往有需求要我们使用另外一个应用或者系统应用的数据,这时候就彰显了内容提供者,ContentPrivider的作用,他就是两个应用数据的桥梁,通过内容提供者和内容接受者我们可以在不同应用间传递数据。
ContentPrivider也可以视为一种数据存储。它存储数据的方式和使用它的应用程序无关,重要的是应用如何以一致的编程接口,来访问存储其中的数据。内容提供者与数据库的使用差不多,也可以增删改查。而且数据可以存储于数据库,文件中,也可以网络上。
简单的定义自己的内容提供者:
首先使用ContentPrivider像使用Activity一样,要再清单文件中注册,注册方法也很简单,在
<span style="white-space:pre"> </span><span style="margin:0px; padding:0px; line-height:1.5"><application></application>节点下注册即可
<span style="white-space:pre"> </span><provider
android:name="com.tai.provider.PersonDBProvider"
android:authorities="com.tai.mylistview.personProvider"/>
android:name ContentProvider的类的全类明名,
android:authorities 可以理解为ContentProvioder的名字,主机名。
还可以制定上权限:android:permission="android.permission.WRITE_SYNC_SETTINGS" 。
Add a URI to match, and the code to return when this URI is matched. URI nodes may be exact match string, the token "*" that matches any text, or the token "#" that matches only numbers.
Starting from API level android.os.Build.VERSION_CODES.JELLY_BEAN_MR2
, this method will accept leading slash in the path.
-
Parameters:
- authority the authority to match
- path the path to match. * may be used as a wild card for any text, and # may be used as a wild card for numbers.
- code the code that is returned when a URI is matched against the given components. Must be positive.
再声明一个继承自ContentProvider的类,来制定内容提供者的方法。
package com.tai.provider;
import com.tai.db.PersonDBOpenHelper;
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 PersonDBProvider extends ContentProvider {
/**
* 使用contentProvider必须要再清单文件中注册
* content://com.tai.mylistview.personProvider/insert
* content://com.tai.mylistview.personProvider/query
* content://com.tai.mylistview.personProvider/delete
* content://com.tai.mylistview.personProvider/update
*/
private static final int INSERT= 1;
private static final int DELETE= 2;
private static final int UPDATE= 3;
private static final int QUERY= 4;
private static final int QUERYONE = 5;
//定义一个Uri的匹配器,用于匹配Uri,如果路径不满足条件 返回-1 UriMatcher.NO_MATCH =-1
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private PersonDBOpenHelper helper;
static{
//添加一组匹配规则
//第一个参数是主机名 再清单文件中注册的时候的 authority
matcher.addURI("com.tai.mylistview.personProvider", "insert", INSERT);
matcher.addURI("com.tai.mylistview.personProvider", "delete", DELETE);
matcher.addURI("com.tai.mylistview.personProvider", "update", UPDATE);
matcher.addURI("com.tai.mylistview.personProvider", "query", QUERY);
matcher.addURI("com.tai.mylistview.personProvider", "query/#", QUERYONE);
}
//在内容提供者创建的额时候
@Override
public boolean onCreate() {
helper = new PersonDBOpenHelper(getContext());
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Cursor cursor;
if( matcher.match(uri) == QUERY)
{//返回查询结果集
SQLiteDatabase database = helper.getReadableDatabase();
cursor = database.query("person",projection , selection, selectionArgs, null, null, sortOrder);
}
else if (matcher.match(uri)==QUERYONE)
{
long id = ContentUris.parseId(uri);//取出rui的最后位的ID
SQLiteDatabase database = helper.getReadableDatabase();
cursor = database.query("person",projection, "id = ?", new String[]{id+""}, null, null, sortOrder);
}
else
{
throw new IllegalArgumentException("路径不匹配,不能执行查询操作");
}
//这里的数据库不能关闭了,关闭之后Cursor就拿不到数据了
return cursor;
}
@Override
public String getType(Uri uri) {
if( matcher.match(uri) == QUERY)
{//查询的是多条数据
return "vnd.android.cursor.dir/persons";
}
else if (matcher.match(uri)==QUERYONE)
{//查询的是一条具体的数据
return "vnd.android.cursor.item";
}
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
if( matcher.match(uri) == INSERT)
{
SQLiteDatabase database = helper.getWritableDatabase();
long id = database.insert("person", null, values);
}
else
{
throw new IllegalArgumentException("路径不匹配,不能执行查询操作");
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
long id ;
if( matcher.match(uri) == DELETE)
{
SQLiteDatabase database = helper.getWritableDatabase();
id = database.delete("person", selection, selectionArgs);
}
else
{
throw new IllegalArgumentException("路径不匹配,不能执行查询操作");
}
return (int) id;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
long id;
if( matcher.match(uri) == UPDATE)
{
SQLiteDatabase database = helper.getWritableDatabase();
id = database.update("person", values, selection, selectionArgs);
}
else
{
throw new IllegalArgumentException("路径不匹配,不能执行查询操作");
}
return (int) id;
}
}
ok,这样就定义好了自己的内容提供者,也就向外部应用提供了正删改查自己数据库的接口。现在就可以新建一个类来使用这个内容提供者了。
如果在定义的时候加上了权限那么在使用的时候也要加上相应的权限,否则无法使用。
针对上面的内容提供者的使用方法:
package com.tai.other;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button button;
private Button button2;
private Button button3;
private Button button4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initview();
initData();
}
//查 增 修改 删除
private void initData() {
// TODO Auto-generated method stub
button = (Button) findViewById(R.id.button);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}
private void initview() {
// TODO Auto-generated method stub
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentResolver contentResolver = getContentResolver();
switch (v.getId()) {
case R.id.button:
Uri uri = Uri.parse("content://com.tai.mylistview.personProvider/query");
Cursor cursor = contentResolver.query(uri, null, null,
null, null);
while(cursor.moveToNext())
{
Log.i("MyTag", cursor.getString(cursor.getColumnIndex("name")));
}
cursor.close();
break;
case R.id.button2:
Uri uri2 = Uri.parse("content://com.tai.mylistview.personProvider/insert");
ContentValues contentValues = new ContentValues();
contentValues.put("name", "zhangsan");
contentValues.put("phone", "15203703331");
contentResolver.insert(uri2, contentValues);
break;
case R.id.button3:
Uri uri3 = Uri.parse("content://com.tai.mylistview.personProvider/update");
ContentValues contentValues2 = new ContentValues();
contentValues2.put("phone", "1520370123");
int id = contentResolver.update(uri3, contentValues2, "name=?", new String[]{"zhangsan"});
Log.i("MyTag", id +"新增后的id");
break;
case R.id.button4:
Uri uri4 = Uri.parse("content://com.tai.mylistview.personProvider/delete");
int id2 = contentResolver.delete(uri4, "name=?", new String[]{"zhangsan"});
Log.i("MyTag", id2 +"删除后的id");
break;
default:
break;
}
}
}
Ok 这就是内容提供者的简单创建以及使用。