17 一个ContentProvider的例子

服务端(ContentProvider)

  • 目录结构图:
    这里写图片描述

  • MainActivity.java:

    package com.qf.day17_contentprovider_words_demo2;
    
    import android.app.Activity;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    
    import com.qf.day17_contentprovider_words_demo2.db.MyOpenHelper;
    
    public class MainActivity extends Activity {
    
        private EditText etWord,etChina;
        private ListView lv;
    
    
        private MyOpenHelper helper;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            etWord  = (EditText) findViewById(R.id.et_word);
            etChina  = (EditText) findViewById(R.id.et_china);
            lv = (ListView) findViewById(R.id.lv);
    
            helper = new MyOpenHelper(MainActivity.this);
    
            getData();
        }
    
        //点击事件  提交按钮
        public void MyClick(View v){
    
            String strWord = etWord.getText().toString().trim();
            String strChina= etChina.getText().toString().trim();
            String sql = "insert into tb_words(word,detail)values(?,?)";
            helper.execData(sql, new String[]{strWord,strChina});
    
            getData();
    
        }
    
        public void getData(){
    
            String sql = "select * from tb_words";
            Cursor cursor = helper.queryData(sql, null);
    
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this,
                    R.layout.item, cursor, 
                    new String[]{"word","detail"}, 
                    new int[]{R.id.tv_word,R.id.tv_china}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    
            lv.setAdapter(adapter);
        }
    
    
    
    
    }
    
  • MyOpenHelper.java(数据库类):

    package com.qf.day17_contentprovider_words_demo2.db;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class MyOpenHelper extends SQLiteOpenHelper {
    
        private static final String NAME = "db_words.db";
        private static final int VERSION = 1;
    
        private SQLiteDatabase db;
    
        public MyOpenHelper(Context context, String name, CursorFactory factory,
                int version) {
            super(context, name, factory, version);
            // TODO Auto-generated constructor stub
        }
        public MyOpenHelper(Context context) {
            super(context, NAME, null, VERSION);
            // TODO Auto-generated constructor stub
            db = getReadableDatabase();
        }
    
    
        /**
         * 查询
         * @param sql
         * @param selectionArgs
         * @return
         */
        public Cursor queryData(String sql, String[] selectionArgs){
    
            Cursor cursor = db.rawQuery(sql, selectionArgs);
            return cursor;
    
        }
    
        /**
         * 增加  修改  删除
         * @param sql
         * @param bindArgs
         */
        public  boolean execData(String sql,Object[] bindArgs){
            try {
                if(bindArgs ==null){
                    db.execSQL(sql);
                }else{
                    db.execSQL(sql, bindArgs);
                }
    
                return true;
    
            } catch (Exception e) {
                // TODO: handle exception
            }
            return false;
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            String sql ="create table if not exists tb_words(_id integer primary key autoincrement,word,detail)";
            //此表无作用只作为一个示范
            String sql1 ="create table if not exists tb_newwords(_id integer primary key autoincrement,word,detail)";
            db.execSQL(sql);
            db.execSQL(sql1);
    
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
    
        }
    
    }
    
  • MyContentProvider

    package com.qf.day17_contentprovider_words_demo2;
    
    import com.qf.day17_contentprovider_words_demo2.db.MyOpenHelper;
    
    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;
    
    public class MyContentProvider extends ContentProvider{
    
    
        private MyOpenHelper helper;
        private SQLiteDatabase db;
    
        //com.qf.contentprovider_words.mycontentprovider 用于匹配意图的uri 
        private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
        static{
    
            /**第一个参数 :意图 和清单文件中的authorities 相同
             * 第二个参数 :路径 
             * 第三个参数:对应uri对应编码
             *  通配符 : * 任意文本  #数字
             *  
             * 例子uriMatcher.addURI("aa.bb","cc/#",1)
             * 例子uriMatcher.addURI("aa.bb","cc/*",2)
             * 
             * 如果 在ContentResolver 的意图uri为  aa.bb.cc/3 那么跳转uriMatcher.addURI("aa.bb","cc/#",1)
             * 
             */
            //在内容解析器中只需要 填写 uri即可 例子 : com.qf.contentprovider_words.mycontentprovider/words/123
            //content://com.qf.contentprovider_words.mycontentprovider/words/h
            uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider", "words", 1);
            uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider", "newwords", 2);
            uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider", "words/*", 3);//*匹配任意文本
            uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider", "words_id/#", 4);//*匹配任意数字
            uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider", "words_zh/*", 5);//*匹配任意中文
    
        }
    
    
        @Override
        public boolean onCreate() {
            // TODO Auto-generated method stub
            helper =  new MyOpenHelper(getContext());
            db  = helper.getReadableDatabase();
            return false;
        }
    
    
    
        @Override
        public String getType(Uri uri) {
            // TODO Auto-generated method stub
            return null;
        }
    
    
        @Override
        public Cursor query(Uri uri, String[] projection, String selection,
                String[] selectionArgs, String sortOrder) {
            // TODO Auto-generated method stub
    
            Cursor cursor =null;
    
            switch (uriMatcher.match(uri)) {
            case 1:
                //tb_words表中所有数据
                cursor = db.query("tb_words", projection, selection, selectionArgs, null, null, sortOrder);
    
                break;
            case 2:
                //tb_newwords表中所有数据
                cursor = db.query("tb_newwords", projection, selection, selectionArgs, null, null, sortOrder);
    
                break;
            case 3:
                //tb_words表中符合条件  word
                String data = uri.getLastPathSegment();//获取Uri最后的参数
                cursor = db.query("tb_words", projection, "word like ?", new String[]{data+"%"}, null, null, sortOrder);
    
                break;
            case 4:
                //tb_words表中符合条件 _id
                String data1 = uri.getLastPathSegment();//获取Uri最后的参数
                cursor = db.query("tb_words", projection, "_id = ?", new String[]{data1+""}, null, null, sortOrder);
    
                break;
            case 5:
    
                //tb_words表中符合条件 detail
                String data2 = uri.getLastPathSegment();//获取Uri最后的参数
                cursor = db.query("tb_words", projection, "detail like ?", new String[]{data2+"%"}, null, null, sortOrder);
    
                break;
    
            default:
                break;
            }
    
            return cursor;
        }
    
        @Override
        public Uri insert(Uri uri, ContentValues values) {
            // TODO Auto-generated method stub
    
            Uri resultUri = null;
            switch (uriMatcher.match(uri)) {
            case 1:
    
                long l = db.insert("tb_words", null, values);
                /**
                 * 两种皆可返回正确id
                 */
    //          resultUri = Uri.parse("content://com.qf.contentprovider_words.mycontentprovider/words/"+l);
                resultUri = ContentUris.withAppendedId(uri, l);
                break;
            case 2:
                long l1 = db.insert("tb_newwords", null, values);
                /**
                 * 两种皆可返回正确id
                 */
    //          resultUri = Uri.parse("content://com.qf.contentprovider_words.mycontentprovider/newwords/"+l1);
                resultUri = ContentUris.withAppendedId(uri, l1);
                break;
    
            default:
                break;
            }
            return resultUri;
        }
    
    
    
    
        @Override
        public int update(Uri uri, ContentValues values, String selection,
                String[] selectionArgs) {
            // TODO Auto-generated method stub
            int num =0;
            switch (uriMatcher.match(uri)) {
            case 1:
                num = db.update("tb_words", values, selection, selectionArgs);
                break;
            case 2:
                num = db.update("tb_newwords", values, selection, selectionArgs);
                break;
    
            default:
                break;
            }
            return num;
        }
    
        @Override
        public int delete(Uri uri, String selection, String[] selectionArgs) {
            // TODO Auto-generated method stub
            int num =0;
            switch (uriMatcher.match(uri)) {
            case 1:
                num = db.delete("tb_words", selection, selectionArgs);
                break;
            case 2:
                num = db.delete("tb_newwords", selection, selectionArgs);
                break;
    
            default:
                break;
            }
            return num;
        }
    
    }
    
  • layout布局文件:
    item

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <TextView 
            android:id="@+id/tv_word"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#f00"
            android:textSize="20sp"
            android:text="hello"
            />
        <TextView 
            android:id="@+id/tv_china"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#00f"
            android:textSize="16sp"
            android:text="word"
            />
    
    
    </LinearLayout>
    

    activity_main.xml

    <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:orientation="vertical"
        tools:context=".MainActivity" >
    
    
    
        <EditText
            android:id="@+id/et_word"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入英文单词" />
        <EditText
            android:id="@+id/et_china"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入对应的意思" />
    
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="提交"
            android:onClick="MyClick"
            />
    
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#999900"
            android:text="以下显示单词列表"
            />
    
        <ListView 
            android:id="@+id/lv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="#f00"
            android:dividerHeight="1dp"
            ></ListView>
    
    </LinearLayout>
    

客户端

  • 结构目录:
    这里写图片描述

  • MainActivity.java:

    package com.qf.day17_contentprovider_wordc_demo2;
    
    import java.util.regex.Pattern;
    
    import android.app.Activity;
    import android.content.ContentResolver;
    import android.content.ContentUris;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    
    public class MainActivity extends Activity {
    
        // //content://com.qf.contentprovider_words.mycontentprovider/words/
        // uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider",
        // "words", 1);
        // uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider",
        // "newwords", 2);
        // uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider",
        // "words/*", 3);//*匹配任意文本
        // uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider",
        // "words_id/#", 4);//*匹配任意数字
        // uriMatcher.addURI("com.qf.contentprovider_words.mycontentprovider",
        // "words_zh/*", 5);//*匹配任意中文
        //
    
        private EditText etSearch;
        private ListView lv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            etSearch = (EditText) findViewById(R.id.et_search);
            lv = (ListView) findViewById(R.id.lv);
        }
    
        public void MyClick(View v) {
            // 根据输入文本进行查询
            String strdata = etSearch.getText().toString().trim();
    
            getData(strdata);
    
        }
    
    
    
        // 查询方法
        public void getData(String strdata) {
    
            ContentResolver resolver = getContentResolver();
            Uri uriWords = Uri.parse("content://com.qf.contentprovider_words.mycontentprovider/words");
            Uri uriWordsId = Uri.parse("content://com.qf.contentprovider_words.mycontentprovider/words_id");
            Uri uriWordsZh = Uri.parse("content://com.qf.contentprovider_words.mycontentprovider/words_zh");
            Cursor cursor = null;
            if (TextUtils.isEmpty(strdata)) {// 什么也没输入 直接查询所有
                cursor = resolver.query(uriWords, null, null, null, null);
            } else {
                if (isNumber(strdata)) {// 输入的数据 是否是数值
                    // content://com.qf.contentprovider_words.mycontentprovider/words_id/45
                    // 拼接id 123
                    uriWordsId = ContentUris.withAppendedId(uriWordsId, Long.parseLong(strdata));
                    cursor = resolver.query(uriWordsId, null, null, null, null);
                } else {
                    if (isChina(strdata)) {// 是否是汉字
                        // 拼接中文 张
                        uriWordsZh = Uri.withAppendedPath(uriWordsZh, strdata);
                        cursor = resolver.query(uriWordsZh, null, null, null, null);
                    } else {
                        // 拼接英文字符串 
                        uriWords = Uri.withAppendedPath(uriWords, strdata);
                        cursor = resolver.query(uriWords, null, null, null, null);
                    }
    
                }
            }
    
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, R.layout.item, cursor,
                    new String[] { "word", "detail" }, new int[] { R.id.tv_word, R.id.tv_china },
                    SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    
            lv.setAdapter(adapter);
    
        }
    
        // 判断是否是数字
        public boolean isNumber(String data) {
            Pattern pattern = Pattern.compile("[0-9]+");
            return pattern.matcher(data).matches();
    
        }
    
        // 判断是否是中文
        public boolean isChina(String data) {
            Pattern pattern = Pattern.compile("[u4e00-u9fa5]+");
            return pattern.matcher(data).matches();
    
        }
    
    }
    
  • layout布局:
    activity_main.xml:

    <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:orientation="vertical"
        tools:context=".MainActivity" >
    
        <EditText
            android:id="@+id/et_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入查询内容" />
    
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="提交"
            android:onClick="MyClick"
            />
    
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="以下展示查询内容"
            android:background="#999900"
            />
        <ListView 
            android:id="@+id/lv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            ></ListView>
    
    </LinearLayout>
    

    item.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <TextView 
            android:id="@+id/tv_word"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#f00"
            android:textSize="20sp"
            android:text="hello"
            />
        <TextView 
            android:id="@+id/tv_china"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#00f"
            android:textSize="16sp"
            android:text="word"
            />
    
    
    </LinearLayout>
    
原文地址:https://www.cnblogs.com/muyuge/p/6152240.html