ContentProvider,ContentResolver,ContentObserver

ContentProvider,ContentResolver,ContentObserver
ContentProvider:
/**
 * Created by Administrator on 2018/6/26.
 */


public class ConstantData {
    public static final String DATABASE_NAME = "person.db";
    public static final int DATABASE_VERSION = 4;
    public static final String TABLE_NAME = "person";
    public static final String AUTHORITY = "com.mcxtzhang.flowlayoutmanager.zuimei.mycontentprovider";
    public static final class PersonData implements BaseColumns {
        public static final String TABLE_NAME = "person";
        public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/person");
        public static final String DIR_CONTENT_TYPE = "vnd.android.cursor.dir/";
        public static final String ITEM_CONTENT_TYPE = "vnd.android.cursor.item/";
        public static final int PERSON_CODE = 1;
        public static final int PERSION_ID_CODE = 2;
        public static final String NAME = "name";
        public static final String SONG = "song";
        public static final String DEFAULT_SORT_ORDER = "_id desc";
        public static final UriMatcher uriMatcher;
        static {
            uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
            uriMatcher.addURI(AUTHORITY,"person",PERSON_CODE);
            uriMatcher.addURI(AUTHORITY,"person/#",PERSION_ID_CODE);
        }


    }
}


/**
 * Created by Administrator on 2018/6/26.
 */


public class DBOpenHelper extends SQLiteOpenHelper {
    public DBOpenHelper(Context context){
        super(context,ConstantData.DATABASE_NAME,null,ConstantData.DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + ConstantData.TABLE_NAME
               +"("
                +ConstantData.PersonData._ID + " INTEGER PRIMARY KEY autoincrement,"
                +ConstantData.PersonData.NAME + " varchar(20),"
                +ConstantData.PersonData.SONG + " varchar(100)"
                + ");");
    }


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


/**
 * Created by Administrator on 2018/6/26.
 */


public class MyContentProvider extends ContentProvider {
    private DBOpenHelper dbOpenHelper = null;


    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        switch (ConstantData.PersonData.uriMatcher.match(uri)){
            case ConstantData.PersonData.PERSON_CODE:
                return ConstantData.PersonData.DIR_CONTENT_TYPE;
                case ConstantData.PersonData.PERSION_ID_CODE:
                    return ConstantData.PersonData.ITEM_CONTENT_TYPE;
                    default:
                        throw new IllegalArgumentException("Unknown uri " + uri);
        }
    }


    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        int count = 0;
        switch (ConstantData.PersonData.uriMatcher.match(uri)){
            case ConstantData.PersonData.PERSON_CODE:
                count = db.update(ConstantData.TABLE_NAME,values,selection,selectionArgs);
                break;
                case ConstantData.PersonData.PERSION_ID_CODE:
                    long personid = ContentUris.parseId(uri);
                    String where = "_ID=" + personid;
                    where += !TextUtils.isEmpty(selection)? " and (" + selection + ")" : "";
                    count = db.update(ConstantData.TABLE_NAME,values,where,selectionArgs);
                    break;
                    default:
                        throw new IllegalArgumentException("Unknown uri "+ uri);
        }
        db.close();
        getContext().getContentResolver().notifyChange(uri,null);
        return count;
    }


    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        long id = 0;
        Uri insertUri = null;
        switch (ConstantData.PersonData.uriMatcher.match(uri)){
            case ConstantData.PersonData.PERSON_CODE:
                id = db.insert(ConstantData.TABLE_NAME,null,values);
                insertUri = ContentUris.withAppendedId(uri,id);
                break;
            case ConstantData.PersonData.PERSION_ID_CODE:
                id = db.insert(ConstantData.TABLE_NAME,null,values);
                String path = uri.toString();
                insertUri = Uri.parse(path.substring(0,path.lastIndexOf("/")) + id);
                break;
            default:
               throw new IllegalArgumentException("Unknown uri "+ uri);
        }
        db.close();
        getContext().getContentResolver().notifyChange(uri,null);
        return  insertUri;
    }


    @Override
    public boolean onCreate() {
        dbOpenHelper = new DBOpenHelper(getContext());
        return true;
    }


    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        int count = 0;
        switch (ConstantData.PersonData.uriMatcher.match(uri)){
            case ConstantData.PersonData.PERSON_CODE:
                count = db.delete(ConstantData.TABLE_NAME,selection,selectionArgs);
                break;
                case ConstantData.PersonData.PERSION_ID_CODE:
                    long personid = ContentUris.parseId(uri);
                    String where = "_ID="+personid;
                    where += !TextUtils.isEmpty(selection)? " and (" + selection + ")" : "";
                    count = db.delete(ConstantData.TABLE_NAME,where,selectionArgs);
                    break;
                    default:
                        throw new IllegalArgumentException("Unknown uri " + uri);
        }
        db.close();
        getContext().getContentResolver().notifyChange(uri,null);
        return count;
    }


    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        Cursor cursor = null;
        switch (ConstantData.PersonData.uriMatcher.match(uri)){
            case ConstantData.PersonData.PERSON_CODE:
                cursor = db.query(ConstantData.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
                break;
                case ConstantData.PersonData.PERSION_ID_CODE:
                    long personid = ContentUris.parseId(uri);
                    String where = "_ID=" + personid;
                    where += !TextUtils.isEmpty(selection)? " and (" + selection + ")" : "";
                    cursor = db.query(ConstantData.TABLE_NAME,projection,where,selectionArgs,null,null,sortOrder);
                    break;
                    default:
                        throw new IllegalArgumentException("Unknown uri "+ uri);
        }
//        db.close();
        return cursor;
    }




}


ContentObserver和ContentResolver


public class Main3Activity extends AppCompatActivity {
    private Button insertBtn,deleteBtn,updateBtn,queryBtn;
    private Uri uri = Uri.parse("content://com.mcxtzhang.flowlayoutmanager.zuimei.mycontentprovider/person");
    private int count = 0;
    private ListView songList;
    private PersonObserver personObserver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        insertBtn = (Button)findViewById(R.id.insertBtn);
        deleteBtn = (Button)findViewById(R.id.deleteBtn);
        updateBtn = (Button)findViewById(R.id.updateBtn);
        queryBtn = (Button)findViewById(R.id.queryBtn);
        songList = (ListView)findViewById(R.id.songList);
        final ContentResolver contentResolver = getContentResolver();
        personObserver = new PersonObserver(new Handler());
        insertBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues contentValues = new ContentValues();
                contentValues.put("name","讲真的"+ count);
                contentValues.put("song","今夜特别漫长,有个号码一直被存放");
                contentResolver.insert(uri,contentValues);
                count ++;
            }
        });
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentResolver.delete(uri,"_ID=?",new String[]{"2"});
            }
        });
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues contentValues = new ContentValues();
                contentValues.put("name","鬼迷心窍");
                contentValues.put("song","明明对你念念不忘,无法深藏,爱没爱过想听你讲");
                contentResolver.update(uri,contentValues,"_ID=?",new String[]{"4"});
            }
        });
        queryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor cursor = contentResolver.query(uri,null,null,null,null);
                SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),android.R.layout.activity_list_item,cursor,new String[]{"song"},new int[]{android.R.id.text1});
                songList.setAdapter(adapter);
//                cursor.close();
            }
        });
        contentResolver.registerContentObserver(uri,true,personObserver);
    }


    private void queryDb(){
        Cursor cursor = getContentResolver().query(uri,null,null,null,null);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),android.R.layout.activity_list_item,cursor,new String[]{"song"},new int[]{android.R.id.text1});
        songList.setAdapter(adapter);
    }


    public class PersonObserver extends ContentObserver{
        public PersonObserver(Handler handler){
            super(handler);
        }


        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            queryDb();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(personObserver);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值