Content Provider 总结

1、实现provider接口,提供给其他程序调用

第一步: 在manifest.xml中配置 provider 组件

<provider android:name="MyProvider" android:authorities="com.ruixin.login" />

其中:name表示 自定义继承于ContentProvider的类名(或者加上包名)
    authorities表示主机名,类似域名

第二步: 创建数据库,表用来保存数据

public class DBlite extends SQLiteOpenHelper
{
    public DBlite(Context context)
    {
        super(context, RuiXin.DBNAME, null, RuiXin.VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        // TODO Auto-generated method stub
        db.execSQL("create table " + RuiXin.TNAME + "(" + RuiXin.TID + " integer primary key autoincrement not null," + RuiXin.EMAIL + " text not null," + RuiXin.USERNAME
                + " text not null," + RuiXin.DATE + " interger not null," + RuiXin.SEX + " text not null);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO Auto-generated method stub
    }

    public void add(String email, String username, String date, String sex)
    {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(RuiXin.EMAIL, email);
        values.put(RuiXin.USERNAME, username);
        values.put(RuiXin.DATE, date);
        values.put(RuiXin.SEX, sex);
        db.insert(RuiXin.TNAME, "", values);
    }
}

第三步: 继承ContentProvider类,提供从数据库中获取数据的接口。 也可以是从文件系统等其他的地方获取

public class MyProvider extends ContentProvider
{

    DBlite dBlite;
    SQLiteDatabase db;

    private static final UriMatcher sMatcher;
    static
    {
             /**注册Uri,用来适配传入的 Uri,进行判断,区分处理方式*/
        sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sMatcher.addURI(RuiXin.AUTOHORITY, RuiXin.TNAME, RuiXin.ITEM);
        sMatcher.addURI(RuiXin.AUTOHORITY, RuiXin.TNAME + "/#", RuiXin.ITEM_ID);
    }
    
    public int delete(Uri uri, String selection, String[] selectionArgs)
    {
        db = dBlite.getWritableDatabase();
        int count = 0;
        switch (sMatcher.match(uri))
        {
        case RuiXin.ITEM:
            count = db.delete(RuiXin.TNAME, selection, selectionArgs);
            break;
        case RuiXin.ITEM_ID:
            String id = uri.getPathSegments().get(1);
            count = db.delete(RuiXin.TID, RuiXin.TID + "=" + id + (!TextUtils.isEmpty(RuiXin.TID = "?") ? "AND(" + selection + ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI" + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
    
    public String getType(Uri uri)
    {
        switch (sMatcher.match(uri))
        {
        case RuiXin.ITEM:
            return RuiXin.CONTENT_TYPE;
        case RuiXin.ITEM_ID:
            return RuiXin.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI" + uri);
        }
    }

    public Uri insert(Uri uri, ContentValues values)
    {
        db = dBlite.getWritableDatabase();
        long rowId;
        if (sMatcher.match(uri) != RuiXin.ITEM)
        {
            throw new IllegalArgumentException("Unknown URI" + uri);
        }
        rowId = db.insert(RuiXin.TNAME, RuiXin.TID, values);
        if (rowId > 0)
        {
            Uri noteUri = ContentUris.withAppendedId(RuiXin.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }
        throw new IllegalArgumentException("Unknown URI" + uri);
    }
    
    public boolean onCreate()
    {
        this.dBlite = new DBlite(this.getContext());
        return true;
    }

    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
    {
        db = dBlite.getWritableDatabase();
        Cursor c;
        Log.d("-------", String.valueOf(sMatcher.match(uri)));
        switch (sMatcher.match(uri))
        {
        case RuiXin.ITEM:
            c = db.query(RuiXin.TNAME, projection, selection, selectionArgs, null, null, null);
            break;
        case RuiXin.ITEM_ID:
            String id = uri.getPathSegments().get(1);
            c = db.query(RuiXin.TNAME, projection, RuiXin.TID + "=" + id + (!TextUtils.isEmpty(selection) ? "AND(" + selection + ')' : ""), selectionArgs, null, null, sortOrder);
            break;
        default:
            Log.d("!!!!!!", "Unknown URI" + uri);
            throw new IllegalArgumentException("Unknown URI" + uri);
        }
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
    {
        return 0;
    }
}

第四步:添加数据到数据库中

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

dBlite1.add("4141414@qq", "jay", "2012", "man");
dBlite1.add("4141414@qq", "jay", "2013", "man");
dBlite1.add("4141414@qq", "jay", "2014", "man");
dBlite1.add("4141414@qq", "jay", "2015", "man");
dBlite1.add("4141414@qq", "jay", "2016", "man");

}

2、从ContentProver 中获取数据

获取数据使用 ContentResolver类,对于使用数据库来保存数据,ContentProvider提供接口来实现数据共享的方法。

如果Uri后面没有加id项,表示操作目录/表,如果有id项,表示操作该项。下面的例子就是获取Uri路径下所有的项,而不是某一项。

public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d("cp" , "content provider");
        // 通过contentResolver进行查找
        contentResolver = ContentProviderClientActivity.this.getContentResolver();
        Uri uri = ContentUris.withAppendedId(RuiXin.CONTENT_URI, 3);
        String type = contentResolver.getType(uri);
        Log.d("cp" , type);
        
        Cursor cursor = contentResolver.query(RuiXin.CONTENT_URI, new String[] { RuiXin.EMAIL, RuiXin.USERNAME, RuiXin.DATE, RuiXin.SEX }, null, null, null);
        while (cursor.moveToNext())
        {
            String text = cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL)) + " " + cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME)) + " "+ cursor.getString(cursor.getColumnIndex(RuiXin.DATE)) + " " + cursor.getString(cursor.getColumnIndex(RuiXin.SEX));
            
            Toast.makeText(ContentProviderClientActivity.this,text, Toast.LENGTH_SHORT).show();
            
            Log.d("cp" , text);
        }
        startManagingCursor(cursor); // 查找后关闭游标
    }
    
    
    
    public class RuiXin {
     
    public static final String DBNAME = "ruixinonlinedb"; 
    public static final String TNAME = "ruixinonline";
    public static final int VERSION = 3;
     
    public static String TID = "tid";
    public static final String EMAIL = "email";
    public static final String USERNAME = "username";
    public static final String DATE = "date";
    public static final String SEX = "sex";
     
     
    public static final String AUTOHORITY = "com.ruixin.login";
    public static final int ITEM = 1;
    public static final int ITEM_ID = 2;
     
    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ruixin.login";
    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.ruixin.login";
     
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTOHORITY + "/ruixinonline");
}
posted @ 2012-08-22 21:58  lipeil  阅读(352)  评论(0编辑  收藏  举报