内容提供者

一旦某个应用程序通过contentprovider暴露了自己的数据操作接口,那么不管该应用程序是否启动,其他应用程序可以通过该接口来操作该应用程序内部的数据,包括增删改查。


 本身操作数据库

步骤:
1.新建一个类继承ContentProvider 
 2.在清单文件中写出provider 节点的内容,包括完整类名(name)和主机域名(authorities)(一般用包名+内容提供者的业务含义名称,这个可以叫做联系方式) 


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.simpledatabase"
    android:versionCode="1"
    android:versionName="1.0" >
    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.example.simpledatabase" />
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <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="com.example.simpledatabase.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="com.example.simpledatabase.PersonDBProvider"
            android:authorities="com.example.simpledatabase.personprovider" 
            >
        </provider>
    </application>
</manifest>  

数据库文件本身只能被本应用程序读写,而别的应用程序既不能读也不能写,因此要通过中间人组件来读写数据库获得数据库数据。这个中间人就是contentprovider
要读取数据库内容,首先要保证数据库中有数据,可以执行testAdd()方法先往数据库添加数据(切记!!)
------------------------------------------------------------------
 }
    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }



------------------------------------------------------------------
package com.example.simpledatabase;
import android.content.ContentProvider;
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;
public class PersonDBProvider extends ContentProvider {
    // 定义一个URI匹配器用于匹配uri,如果路径不满足条件则
    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    // 用于规定addURI的返回值
    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 PersonSQLiteOpenHelper helper;
    private String tag="PersonDBProvider";
    // 指定匹配器的规则
    static {
        // 添加一组匹配规则
        matcher.addURI("com.example.simpledatabase.personprovider""insert",
                INSERT);
        matcher.addURI("com.example.simpledatabase.personprovider""delete",
                DELETE);
        matcher.addURI("com.example.simpledatabase.personprovider""update",
                UPDATE);
        matcher.addURI("com.example.simpledatabase.personprovider""query",
                QUERY);
    }
    // 在安卓中内容提供者路径名格式为
    // content://com.example.simpledatabase.personprovider/insert 添加操作
    // content://com.example.simpledatabase.personprovider/update
    // content://com.example.simpledatabase.personprovider/query
    // content://com.example.simpledatabase.personprovider/delete
    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        helper = new PersonSQLiteOpenHelper(getContext());
        return false;
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        if (matcher.match(uri) == QUERY) {
            Log.i(tag"看效果");
            SQLiteDatabase db = helper.getReadableDatabase();
            Cursor cursor = db.query("person", projection, selection,
                    selectionArgs, nullnull, sortOrder);
            return cursor;//不能关闭数据库否则无法获取结果集
        } else {
            throw new IllegalArgumentException("查询失败,路径名不合法");
        }
    }
    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }
}

在别的应用程序里读取数据库可以这样写:


------------------这是布局-----------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.providertest.MainActivity"
    tools:ignore="MergeRootFrame" >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="读取数据库" />
    
      <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="insert"
        android:text="添加数据" />
      
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="delete"
        android:text="删除数据" />
        
          <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="update"
        android:text="修改数据" />
</LinearLayout>

---------------------主程序---------------------

package com.example.providertest;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void click(View view) {
        // 得到手机中间人
        Uri uri = Uri
                .parse("content://com.example.simpledatabase.personprovider/query");
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(uri, nullnullnullnull);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String id = cursor.getString(cursor.getColumnIndex("id"));
            System.out.println("name" + name + "::" + "id" + id);
        }
        cursor.close();
    }

         
    public void delete(View view) {
        Uri uri = Uri
                .parse("content://com.example.simpledatabase.personprovider/delete");
        ContentResolver resolver = getContentResolver();
        resolver.delete(uri, "name=?"new String[]{"wangwu1"});
    }
    
    public void insert(View view) {
        Uri uri = Uri
                .parse("content://com.example.simpledatabase.personprovider/insert");
        ContentResolver resolver = getContentResolver();
        ContentValues values=new ContentValues();
        values.put("number""18825");
        values.put("name""liutao");
        resolver.insert(uri, values);
    }
    public void update(View view) {
        Uri uri = Uri
                .parse("content://com.example.simpledatabase.personprovider/update");
        ContentResolver resolver = getContentResolver();
        ContentValues values=new ContentValues();
        values.put("number""999");
        resolver.update(uri, values, "name=?"new String[]{"wangwu3"});
    }  

}


可以在Logcat中观察是否读取到数据。
切记路径要正确

---------------------------------------------------------------------------





posted @ 2014-07-28 17:16  little-byte  阅读(252)  评论(0)    收藏  举报