学习笔记|AS 数据共享ContentProvider

ContentProvider

ContentProvider提供了更为高级的数据共享方法,应用程序可以指定需要共享的数据,而其他应用程序则可以在不知道数据来源,路径的情况下,对共享数据进行查询、添加,删除和更新等操作。

一定要!一定要!注册 ContentProvider,在AndroidManifest.xml中
在这里插入图片描述

调用者不能直接调用ContentProvider的接口函数,而需要使用ContentResolver对象,通过URI间接调用ContentProvider,调用关系如下图
学习笔记|AS 数据共享ContentProvider_第1张图片
ok!!!!话不多说,直接上图,请看!!!!!!→
学习笔记|AS 数据共享ContentProvider_第2张图片
这个界面没得问题撒,就不多说了(需要源码的评论)。
接下来看下活动工程:
在这里插入图片描述
其中MainActivity是活动工程,People是声明 CONTENT_URI 和构造 Uri,PeopleProvider 是继承 Content Provider。继承Content Provider后,共有六个函数需要重载,分别是delete()、getType()、insert()、onCreate()、query()和updat()。增删查改更新就不同说了,getType()函数用来返回指定URI的MIME数据类型。

我们先来看下People里面的代码:

public class People {
   public static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";//多条数据
   public static final String MIME_ITEM_PREFIX = "vnd.android.cursor.item";//单条数据
   public static final String MINE_ITEM = "vnd.example.a86181.people";
   public static final String MINE_TYPE_SINGLE = MIME_ITEM_PREFIX + "/" + MINE_ITEM;
   public static final String MINE_TYPE_MULTIPLE = MIME_DIR_PREFIX + "/" + MINE_ITEM;

   public static final String AUTHORITY = "com.example.a86181.content.peopleProvider";//授权者名称
   public static final String PATH_SINGLE = "people/#";//单条数据的数据路径
   public static final String PATH_MULTIPLE = "people";//多条数据的数据路径
   public static final String CONTENT_URI_STRING = "content://" + AUTHORITY + "/" + PATH_MULTIPLE;
   public static final Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING);//正式声明

   public static final String KEY_ID = "_id";
   public static final String KEY_NAME = "name";
   public static final String KEY_AGE = "age";
   public static final String KEY_HEIGHT = "height";

}

代码里面都标注的比较清除,我就不做说明了,有不理解的可以评论我。

然后我们在来看PeopleProvider里的代码:

public class PeopleProvider extends ContentProvider {
    //创建名为people的数据库
    //创建名为peopleinfo的数据表
    //版本号为1
    private static final String DB_NAME = "people.db";
    private static final String DB_TABLE = "peopleinfo";
    private static final int DB_VERSION = 1;

    private SQLiteDatabase db;
    private DBOpenHelper dbOpenHelper;

    private static final int MULTIPLE_PEOPLE = 1;
    private static final int SINGLE_PEOPLE = 2;
    private static final UriMatcher uriMatcher;
//声明UriMatcher的匹配方式和返回代码
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(People.AUTHORITY, People.PATH_MULTIPLE, MULTIPLE_PEOPLE);
        uriMatcher.addURI(People.AUTHORITY, People.PATH_SINGLE, SINGLE_PEOPLE);
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
            case MULTIPLE_PEOPLE:
                return People.MINE_TYPE_MULTIPLE;
            case SINGLE_PEOPLE:
                return People.MINE_TYPE_SINGLE;
            default:
                throw new IllegalArgumentException("Unkown uri:" + uri);
        }
    }

    @Override
    //删除操作
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
        switch (uriMatcher.match(uri)) {
            case MULTIPLE_PEOPLE:
                //删除全部数据
                count = db.delete(DB_TABLE, selection, selectionArgs);
                break;
            case SINGLE_PEOPLE:
                //根据指定id删除相应的数据
                String segment = uri.getPathSegments().get(1);
                count = db.delete(DB_TABLE, People.KEY_ID + "=" + segment, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    //添加操作
    public Uri insert(Uri uri, ContentValues values) {
        long id = db.insert(DB_TABLE, null, values);
        if (id > 0) {
            Uri newUri = ContentUris.withAppendedId(People.CONTENT_URI, id);
            getContext().getContentResolver().notifyChange(newUri, null);
            return newUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    //初始化数据集和建立数据连接
    public boolean onCreate() {
        Context context = getContext();
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        db = dbOpenHelper.getWritableDatabase();

        if (db == null) return false;
        else return true;
    }

    @Override
    //查询操作
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(DB_TABLE);
        switch (uriMatcher.match(uri)) {
            case SINGLE_PEOPLE:
                //根据指定id查询相应数据
                qb.appendWhere(People.KEY_ID + "=" + uri.getPathSegments().get(1));
                break;
            default:
                break;
        }
        //查询全部
        Cursor cursor = qb.query(db,projection,selection,selectionArgs,null,null,sortOrder);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    //更新操作
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        int count;
        switch (uriMatcher.match(uri)) {
            case MULTIPLE_PEOPLE:
                //跟新全部
                count = db.update(DB_TABLE, values, selection, selectionArgs);
                break;
            case SINGLE_PEOPLE:
                //更新指定id的数据
                String segment = uri.getPathSegments().get(1);
                count = db.update(DB_TABLE, values, People.KEY_ID + "=" + segment, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknow URI:" + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

//创建数据库操作
    private static class DBOpenHelper extends SQLiteOpenHelper {

        public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        private static final String DB_CREATE = "create table " + DB_TABLE + " (" + People.KEY_ID + " integer primary key autoincrement, " + People.KEY_NAME + " text not null, " + People.KEY_AGE + " integer," + People.KEY_HEIGHT + " float);";

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
            onCreate(_db);
        }
    }
}

代码里写的都很清楚了,就不做说明了。

最后再来看MainActivity里的代码:

public class MainActivity extends AppCompatActivity {
    private EditText nameText;
    private EditText ageText;
    private EditText heightText;
    private EditText idEntry;

    private TextView labelView;
    private TextView displayView;

    private ContentResolver resolver;
    
    addButtonListener addButtonListener = new addButtonListener();
    queryAllButtonListener queryAllButtonListener = new queryAllButtonListener();
    clearButtonListener clearButtonListener = new clearButtonListener();
    deleteAllButtonListener deleteAllButtonListener = new deleteAllButtonListener();
    queryButtonListener queryButtonListener = new queryButtonListener();
    deleteButtonListener deleteButtonListener = new deleteButtonListener();
    updateButtonListener updateButtonListener = new updateButtonListener();

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

        nameText = (EditText) findViewById(R.id.name);
        ageText = (EditText) findViewById(R.id.age);
        heightText = (EditText) findViewById(R.id.height);
        idEntry = (EditText) findViewById(R.id.id_entry);

        labelView = (TextView) findViewById(R.id.label);
        displayView = (TextView) findViewById(R.id.display);

        Button addButton = (Button) findViewById(R.id.add);
        Button queryAllButton = (Button) findViewById(R.id.query_all);
        Button clearButton = (Button) findViewById(R.id.clear);
        Button deleteAllButton = (Button) findViewById(R.id.delete_all);

        Button queryButton = (Button) findViewById(R.id.query);
        Button deleteButton = (Button) findViewById(R.id.delete);
        Button updateButton = (Button) findViewById(R.id.update);


        addButton.setOnClickListener(addButtonListener);
        queryAllButton.setOnClickListener(queryAllButtonListener);
        clearButton.setOnClickListener(clearButtonListener);
        deleteAllButton.setOnClickListener(deleteAllButtonListener);

        queryButton.setOnClickListener(queryButtonListener);
        deleteButton.setOnClickListener(deleteButtonListener);
        updateButton.setOnClickListener(updateButtonListener);

        resolver = this.getContentResolver();

    }

    private class addButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            ContentValues values = new ContentValues();

            values.put(People.KEY_NAME,nameText.getText().toString());
            values.put(People.KEY_AGE,Integer.parseInt(ageText.getText().toString()));
            values.put(People.KEY_HEIGHT, Float.parseFloat(heightText.getText().toString()));

            Uri newUri = resolver.insert(People.CONTENT_URI, values);

            labelView.setText("添加成功,URI:" + newUri);

        }
    }

    ;

    private class queryAllButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Cursor cursor = resolver.query(People.CONTENT_URI, new String[]{People.KEY_ID, People.KEY_NAME, People.KEY_AGE, People.KEY_HEIGHT}, null, null, null);
            if (cursor == null) {
                labelView.setText("数据库中没有数据");
                return;
            }
            labelView.setText("数据库:" + String.valueOf(cursor.getCount()) + "条记录");

            String msg = "";
            if (cursor.moveToFirst()) {
                do {
                    msg += "ID:" + cursor.getInt(cursor.getColumnIndex(People.KEY_ID)) + ",";
                    msg += "姓名:" + cursor.getString(cursor.getColumnIndex(People.KEY_NAME)) + ",";
                    msg += "年龄:" + cursor.getInt(cursor.getColumnIndex(People.KEY_AGE)) + ", ";
                    msg += "身高:" + cursor.getFloat(cursor.getColumnIndex(People.KEY_HEIGHT)) + "\n";
                } while (cursor.moveToNext());
            }
            displayView.setText(msg);
        }
    }

    ;

    private class clearButtonListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            displayView.setText("");
        }
    }

    ;

    private class deleteAllButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            resolver.delete(People.CONTENT_URI, null, null);
            String msg = "数据全部删除";
            labelView.setText(msg);
        }
    }

    ;

    private class queryButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + idEntry.getText().toString());
            Cursor cursor = resolver.query(uri, new String[]{People.KEY_ID, People.KEY_NAME, People.KEY_AGE, People.KEY_HEIGHT}, null, null, null);
            if (cursor == null) {
                labelView.setText("数据库中没有数据");
                return;
            }

            String msg = "";
            if (cursor.moveToFirst()) {
                msg += "ID:" + cursor.getInt(cursor.getColumnIndex(People.KEY_ID)) + ",";
                msg += "姓名:" + cursor.getString(cursor.getColumnIndex(People.KEY_NAME)) + ",";
                msg += "年龄:" + cursor.getInt(cursor.getColumnIndex(People.KEY_AGE)) + ", ";
                msg += "身高:" + cursor.getFloat(cursor.getColumnIndex(People.KEY_HEIGHT)) + "\n";
            }
            labelView.setText("数据库:");
            displayView.setText(msg);
        }
    }

    ;

    private class deleteButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + idEntry.getText().toString());
            int result = resolver.delete(uri, null, null);
            String msg = "删除ID为" + idEntry.getText().toString() + "的数据" + (result > 0 ? "成功" : "失败");
            labelView.setText(msg);
        }
    }

    ;

    private class updateButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            ContentValues values = new ContentValues();

            values.put(People.KEY_NAME, nameText.getText().toString());
            values.put(People.KEY_AGE, Integer.parseInt(ageText.getText().toString()));
            values.put(People.KEY_HEIGHT, Float.parseFloat(heightText.getText().toString()));

            Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + idEntry.getText().toString());
            int result = resolver.update(uri, values, null, null);

            String msg = "更新ID为" + idEntry.getText().toString() + "的数据" + (result > 0 ? "成功" : "失败");
            labelView.setText(msg);
        }
    }

    ;
}

对应的增删查改等基本操作都在里面了。代码根据相应的英文也很容易理解,就不一 一说明了,有部分不理解的欢迎评论。

展示成果了!!!!!
学习笔记|AS 数据共享ContentProvider_第3张图片
学习笔记|AS 数据共享ContentProvider_第4张图片
学习笔记|AS 数据共享ContentProvider_第5张图片
学习笔记|AS 数据共享ContentProvider_第6张图片
说明一下清除数据指的是,把显示的数据弄成不显示,display空
学习笔记|AS 数据共享ContentProvider_第7张图片
后面的ID删除,ID查询,ID更新就不操作了。但是,是可以操作的,有需要的把代码考下来自己演示哦。

刚开始写,也不知道怎么把自己的想法表示出来,反正不懂就问。就这么简单!

你可能感兴趣的:(Android学习)