美文网首页
ContentProvider使用示例

ContentProvider使用示例

作者: 小竹排丶 | 来源:发表于2018-11-13 17:00 被阅读0次

    1、MyContentProvider

    public class MyContentProviderextends ContentProvider {

    private static final StringTAG ="MyContentProvider";

        private Contextcontext;

        private SQLiteDatabasesqLiteDatabase;

        public static final StringAUTHORITY ="com.examp.mycontentprovider.MyContentProvider";

        public static final int PROVIDER_CODE =0;

        private static final UriMatcheruriMatcher =new UriMatcher(UriMatcher.NO_MATCH);

        static {

                uriMatcher.addURI(AUTHORITY, MyDBHelper.TABLE_NAME, PROVIDER_CODE);

        }

        public MyContentProvider() {

        }

        /**

        * 通过uri匹配表名

        *

        * @param uri

        * @return

        */

        private StringgetTableName(Uri uri) {

            String tableName =null;

            switch (uriMatcher.match(uri)) {

                    case PROVIDER_CODE:

                    tableName = MyDBHelper.TABLE_NAME;

                    break;

            }

            return tableName;

        }

    @Override

        public boolean onCreate() {

                init();

        return false;

        }

        private void init() {

            context = getContext();

            sqLiteDatabase =new MyDBHelper(context).getWritableDatabase();

        }

    @Nullable

    @Override

        public Cursorquery(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {

            String tableName = getTableName(uri);

            if (tableName ==null) {

                Log.e(TAG, "query: 未匹配到uri");

                throw new IllegalArgumentException("Unsupported URI:" + uri);

            }

            return sqLiteDatabase.query(tableName, projection, selection, selectionArgs, null, null,             sortOrder, null);

        }

    @Nullable

    @Override

        public StringgetType(@NonNull Uri uri) {

            return null;

        }

        @Nullable

        @Override

        public Uriinsert(@NonNull Uri uri, @Nullable ContentValues values) {

                String tableName = getTableName(uri);

                if (tableName ==null) {

                Log.e(TAG, "insert: 未匹配到uri");

                throw new IllegalArgumentException("Unsupported URI:" + uri);

                }

                sqLiteDatabase.insert(tableName, null, values);

                context.getContentResolver().notifyChange(uri, null);

                Log.d(TAG, "insert: 添加成功");

                return uri;

        }

        @Override

        public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {

                String tableName = getTableName(uri);

                if (tableName ==null) {

                Log.e(TAG, "delete: 未匹配到uri");

                throw new IllegalArgumentException("Unsupported URI:" + uri);

                }

                int count =sqLiteDatabase.delete(tableName, selection, selectionArgs);

                if (count >0) {

                context.getContentResolver().notifyChange(uri, null);

            }

                Log.d(TAG, "delete: 删除成功");

                Log.d(TAG, "delete: count=" + count);

            return count;

        }

        @Override

        public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {

                String tableName = getTableName(uri);

                if (tableName ==null) {

                    throw new IllegalArgumentException("Unsupported URI:" + uri);

                }

                int row =sqLiteDatabase.update(tableName, values, selection, selectionArgs);

                if (row >0) {

                    context.getContentResolver().notifyChange(uri, null);

            }

            return row;

        }

    }


    2、MyDBHelper

    public class MyDBHelperextends SQLiteOpenHelper {

    /**

    * 库名

    */

        private static final StringDBNAME ="provider.db";

        /**

    * 表明 测试用

    */

        public static final StringTABLE_NAME ="provider_data";

        /**

    * 版本号

    */

        private static final int VERSION =1;

        /**

        * 建表的sql语句

        */

        private static final StringSQL ="create table " +TABLE_NAME +"(id integer primary key Autoincrement,name text)";

        private Contextcontext;

        public MyDBHelper(Context context) {

            super(context, DBNAME, null, VERSION);

            this.context = context;

        }

    @Override

        public void onCreate(SQLiteDatabase db) {

            db.execSQL(SQL);

            Toast.makeText(context, "建表成功", Toast.LENGTH_SHORT).show();

            Log.d("MyContentProvider", "onCreate: 建表成功");

        }

        @Override

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

        }

    }


    3、在MainActivity中使用

    public class MainActivityextends AppCompatActivityimplements View.OnClickListener {

    private static final StringTAG ="MyContentProvider";

        @Override

        protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            initView();

        }

    private void initView() {

            Button bt_init = findViewById(R.id.bt_init);

            bt_init.setOnClickListener(this);

            Button bt_add = findViewById(R.id.bt_add);

            bt_add.setOnClickListener(this);

            Button bt_delete = findViewById(R.id.bt_delete);

            bt_delete.setOnClickListener(this);

            Button bt_update = findViewById(R.id.bt_update);

            bt_update.setOnClickListener(this);

            Button bt_query = findViewById(R.id.bt_query);

            bt_query.setOnClickListener(this);

        }

    @Override

        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.bt_init:

                        init();

                    break;

                case R.id.bt_add:

                        toAdd();

                    break;

                case R.id.bt_delete:

                    toDelete();

                    break;

                case R.id.bt_update:

                    toUpdate();

                break;

                case R.id.bt_query:

                    toQuery();

                break;

            }

    }

        private void init() {

            getContentResolver().delete(nameUri, null, null);

        }

        private UrinameUri = Uri.parse("content://com.examp.mycontentprovider.MyContentProvider/provider_data");

        private void toAdd() {

            ContentValues contentValues =new ContentValues();

            contentValues.put("name", "水货");

            getContentResolver().insert(nameUri, contentValues);

        }

        private void toDelete() {

                getContentResolver().delete(nameUri, "name=?", new String[]{"水货"});

        }

        private void toUpdate() {

            ContentValues contentValues =new ContentValues();

            contentValues.put("name", "太阳");

            getContentResolver().update(nameUri, contentValues, "id=?", new String[]{"21"});

        }

    private void toQuery() {

                Cursor nameCursor = getContentResolver().query(nameUri, new String[]{"id", "name"}, null, null, null);

                if (nameCursor !=null) {

                    while (nameCursor.moveToNext()) {

                    Log.e(TAG, "id:" + nameCursor.getInt(nameCursor.getColumnIndex("id"))

                    +" name:" + nameCursor.getString(nameCursor.getColumnIndex("name")));

                }

                    Log.d(TAG, "toQuery: 查询成功");

                    nameCursor.close();

            }

        }

    }


    4、activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        xmlns:tools="http://schemas.android.com/tools"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:gravity="center_horizontal"

        android:orientation="vertical"

        tools:context=".MainActivity">

            android:id="@+id/bt_init"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="初始化" />

            android:id="@+id/bt_add"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="添加" />

            android:id="@+id/bt_delete"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="删除" />

            android:id="@+id/bt_update"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="更新" />

            android:id="@+id/bt_query"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="查询" />

    </LinearLayout>


    5、manifest

    <?xml version="1.0" encoding="utf-8"?>

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"

        package="com.examp.mycontentprovider">

            android:allowBackup="true"

            android:icon="@mipmap/ic_launcher"

            android:label="@string/app_name"

            android:roundIcon="@mipmap/ic_launcher_round"

            android:supportsRtl="true"

            android:theme="@style/AppTheme">

            <activity android:name=".MainActivity">

                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />

                android:name=".MyContentProvider"

                android:authorities="com.examp.mycontentprovider.MyContentProvider"

                android:exported="true"/>

    </manifest>

    相关文章

      网友评论

          本文标题:ContentProvider使用示例

          本文链接:https://www.haomeiwen.com/subject/sculfqtx.html