Android 使用ContentProvider ContentResolver 实现增删改查



1.ContentProvider

package com.hh.beauter.contentprovider;

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.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by Hh on 2017/1/22.
 * 操作person 表的provider
 */

public class PersonProvider extends ContentProvider {
    //实现insert delete update query 等方法
    private static final String TAG = "haoren";
    //用来存放所有合法的Uri的容器
    private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    private DBHelper dbHelper;
    //保存一些合法的uri
    static {
        //content://com.hh.beauter.contentprovider.personprovider/person 不根据id操作
        //content://com.hh.beauter.contentprovider.personprovider/person/#  根据id操作
        uriMatcher.addURI("com.hh.beauter.contentprovider.personprovider", "/person", 1);
        //#匹配任意数字
        uriMatcher.addURI("com.hh.beauter.contentprovider.personprovider", "/person/#", 2);
    }

    public PersonProvider() {
        Log.e(TAG, "PersonProvider: +++++++++++++");
    }

    @Override
    public boolean onCreate() {
        Log.e(TAG, "onCreate: ");
        dbHelper = new DBHelper(getContext());
        return false;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.e(TAG, "query: ");
        //匹配Uri,返回code
        int code = uriMatcher.match(uri);
        //得到连接对象
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        //如果合法,进行对应的操作
        if (code == 1) {
            //不根据id 查询
            Cursor cursor = database.query("person", projection, selection, selectionArgs, null, null, null);
            return cursor;
        } else if (code == 2) {
            //根据id 查询
            //得到id
            long id = ContentUris.parseId(uri);
            //查询
            Cursor cursor = database.query("person", projection,
                    selection, new String[]{id + ""}, "_id=?", null, null, null);
            return cursor;
        } else {
            //如果不合法,抛出异常
            throw new RuntimeException("查询的uri不合法");
        }
    }


    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        Log.d(TAG, "insert: ");
        //得到连接对象
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        //匹配Uri,返回code
        int code = uriMatcher.match(uri);
        //如果合法,进行对应的操作
        if (code == 1) {
            long id = database.insert("person", null, values);
            //将id添加到uri中
            uri = ContentUris.withAppendedId(uri, id);
            database.close();
            return uri;
        } else {
            database.close();
            //如果不合法,抛出异常
            throw new RuntimeException("添加的uri不合法");
        }
    }


    /**
     * content://com.hh.beauter.contentprovider.personprovider/person 不根据id操作
     * content://com.hh.beauter.contentprovider.personprovider/person/#  根据id操作
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        Log.d(TAG, "delete: ");
        //得到连接对象
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        //匹配Uri,返回code
        int code = uriMatcher.match(uri);
        int deleteCount = -1;
        //如果合法,进行对应的操作
        if (code == 1) {
            deleteCount = database.delete("person", selection, selectionArgs);
        } else if (code == 2) {
            long id = ContentUris.parseId(uri);
            deleteCount = database.delete("person", "_id=" + id, null);
        } else {
            database.close();
            //如果不合法,抛出异常
            throw new RuntimeException("删除的uri不合法");
        }
        return deleteCount;
    }

    /**
     * content://com.hh.beauter.contentprovider.personprovider/person 不根据id操作
     * content://com.hh.beauter.contentprovider.personprovider/person/#  根据id操作
     * @param uri
     * @param values
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        Log.d(TAG, "update: ");

        //得到连接对象
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        //匹配Uri,返回code
        int code = uriMatcher.match(uri);
        int updateCount = -1;
        //如果合法,进行对应的操作
        if (code == 1) {
            updateCount = database.update("person", values, selection, selectionArgs);
        } else if (code == 2) {
            long id = ContentUris.parseId(uri);
            updateCount = database.update("person",values, "_id=" + id, null);
        } else {
            database.close();
            //如果不合法,抛出异常
            throw new RuntimeException("更新的uri不合法");
        }
        return updateCount;
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        Log.d(TAG, "getType: ");
        return null;
    }

}
2.DBHelper

package com.hh.beauter.contentprovider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by Hh on 2017/1/22.
 */

public class DBHelper extends SQLiteOpenHelper{
    public DBHelper(Context context) {
        super(context, "haoren.db", null, 1);
    }

    private static final String TAG = "haoren";

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.e(TAG, "onCreate:+++++ " );
        //建表
        db.execSQL("create table person(_id integer primary key autoincrement,name varchar)");
        //插入初始化数据
        db.execSQL("insert into person (name) values ('Midi')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

3.ContentResolver

package com.jereh.learnbymyself.contentResolver;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.jereh.learnbymyself.R;

public class ResolverActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resolver);
    }

    public void select(View view) {
        //得到ContentResolver对象
        ContentResolver contentResolver = getContentResolver();
        //调用query,得到cursor
        Uri uri = Uri.parse("content://com.hh.beauter.contentprovider.personprovider/person");
        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        //去除cursor总的数据 并显示
        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            Toast.makeText(this, "id:" + id + "name:" + name, Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }

    public void insert(View view) {
        //得到ContentResolver对象
        ContentResolver contentResolver = getContentResolver();
        //调用insert,
        Uri uri = Uri.parse("content://com.hh.beauter.contentprovider.personprovider/person/");
        ContentValues values = new ContentValues();
        values.put("name", "Jack");
        uri = contentResolver.insert(uri, values);
        Toast.makeText(this, "插入成功" + uri.toString(), Toast.LENGTH_SHORT).show();
    }

    public void update(View view) {
        //得到ContentResolver对象
        ContentResolver contentResolver = getContentResolver();
        //调用insert,
        Uri uri = Uri.parse("content://com.hh.beauter.contentprovider.personprovider/person/2");
        ContentValues values = new ContentValues();
        values.put("name", "JackUp");
        int updateConut = contentResolver.update(uri, values, null, null);
        Toast.makeText(this, "更新成功" + updateConut, Toast.LENGTH_SHORT).show();
    }

    public void delete(View view) {
        //得到ContentResolver对象
        ContentResolver contentResolver = getContentResolver();
        //调用insert,
        Uri uri = Uri.parse("content://com.hh.beauter.contentprovider.personprovider/person/2");
        int deleteConut = contentResolver.delete(uri, null, null);
        Toast.makeText(this, "删除" + deleteConut, Toast.LENGTH_SHORT).show();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值