美文网首页
ContentProvider示例

ContentProvider示例

作者: I_Gisvity | 来源:发表于2017-01-14 15:39 被阅读0次

    1.创建数据提供者数据库

    public class DBhelper extends SQLiteOpenHelper {
    
        public DBhelper(Context context){
            super(context,"test.db",null,1);
        }
    
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            String sqlCreateTable ="create Table t_test ( id  integer primary key autoincrement , name text )";
            sqLiteDatabase.execSQL(sqlCreateTable);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    
        }
    }
    

    2.创建数据提供接口页面,继承ContentProvider

    public class MyContentProvider extends ContentProvider {
    
    
        private DBhelper dbhelper;
        private SQLiteDatabase dataBase;
    
        @Override
        public boolean onCreate() {
            dbhelper = new DBhelper(getContext());
            dataBase = dbhelper.getReadableDatabase();
            return false;
        }
    
        @Override
        public String getType(Uri uri) {
            return "";
        }
    
        @Nullable
        @Override
        public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
            Cursor cursor = null;
            cursor = dataBase.query(uri.getLastPathSegment(), projection, selection, selectionArgs, null, null, sortOrder);
            return cursor;
        }
    
        @Nullable
        @Override
        public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
            return null;
        }
    
        @Override
        public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
            return 0;
        }
    
        @Override
        public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
            return 0;
        }
    }
    
    

    3.注册

            <provider
                android:authorities="com.czos.exp"
                android:exported="true"
                android:name=".MyContentProvider">
            </provider>
    

    4.B程序中调用数据

            String uriStr ="content://com.czos.exp/t_test";
            Uri uri  = Uri.parse(uriStr);
            contentS = getContentResolver();
            Cursor cursor = contentS.query(uri,null,null,null,null);
            while (cursor.moveToNext()){
                int id =cursor.getInt(0);
                String name =cursor.getString(1);
                Log.d("ContentResolver","id:"+id+" name:"+name);
            }
    

    源代码

    相关文章

      网友评论

          本文标题:ContentProvider示例

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