天天看點

ContentProvider,ContentResolver,ContentObserver

ContentProvider,ContentResolver,ContentObserver

ContentProvider:

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);

        }

    }

}

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) {

    }

}

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);

    }

}