欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android之ContentProvider(内容的提供者)与ContentResolver(内容访问者)

程序员文章站 2024-02-11 14:01:58
...
内容的提供者(ContentProvider)

1.作用:
    暴露本应用的私有数据,供其他应用使用。通过继承ContentProvider。
有选择地暴露插入、删除、修改和查询本应用数据的接口。

2.使用:
    继承ContentProvider抽象类,并选择性地增删改查方法



需要在清单文件中配置
authorities为包名
name为继承ContentProvider的那个类

 
<!--配置内容提供者-->
        <provider
            android:authorities="com.zking.administrator.g160618_android16_sqlite.LOGIN"
            android:name=".MyProvider"
            android:exported="true"
            ></provider>



内容访问者(ContentResolver)

1. 作用
访问内容提供者,并解析返回的数据

2. 使用
通过上下文对象获取内容解析者

ContentResolver resolver = this.getContentResolver();



下面举一个实例,只在调用,操作时打印结果。

新建一个Moudle:
新建一个db连接数据库的包DBHelper
    package com.zking.db;  
      
    import android.content.Context;  
    import android.database.sqlite.SQLiteDatabase;  
    import android.database.sqlite.SQLiteOpenHelper;  
    import android.util.Log;  
      
    /**  
     * Created by Administrator on 2017/6/27 0027.  
     */  
      
    public class DBHelper extends SQLiteOpenHelper {  
        /**  
         *  
         * @param context   上下文  
         * @param name       数据库名字(文件名)  
         * @param factory   数据库工厂  :null  
         * @param version    数据库版本  
         */  
        public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {  
            super(context, name, factory, version);  
            Log.i("test","构造方法");  
        }  
        //创建表  
        @Override  
        public void onCreate(SQLiteDatabase db) {  
            Log.i("test","创建表");  
            db.execSQL("create table login(uid integer primary key autoincrement,uname,upass)");  
        }  
        @Override  
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
            Log.i("test","升级");  
        }  
      
    //    @Override  
    //    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
    //        super.onDowngrade(db, oldVersion, newVersion);  
    //    }  
    }  


在activity_main.xml中这样写
    <?xml version="1.0" encoding="utf-8"?>  
    <LinearLayout  
        xmlns:android="http://schemas.android.com/apk/res/android"  
        xmlns:app="http://schemas.android.com/apk/res-auto"  
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:orientation="vertical"  
        tools:context="com.zking.administrator.g160618_android16_sqlite.MainActivity">  
      
        <EditText  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:hint="用户名:"  
            android:id="@+id/et_main_uname"  
            />  
        <EditText  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:hint="密码:"  
            android:id="@+id/et_main_upass"  
            />  
        <Button  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:text="操作"  
            android:onClick="operation"  
            />  
      
      
    </LinearLayout>  


然后在与xml相对应的java代码中MainActivity添加数据到数据库中
    package com.zking.administrator.g160618_android16_sqlite;  
      
    import android.content.ContentValues;  
    import android.database.Cursor;  
    import android.database.sqlite.SQLiteDatabase;  
    import android.support.v7.app.AppCompatActivity;  
    import android.os.Bundle;  
    import android.util.Log;  
    import android.view.View;  
    import android.widget.EditText;  
    import android.widget.Toast;  
      
    import com.zking.db.DBHelper;  
      
    public class MainActivity extends AppCompatActivity {  
      
        private EditText et_main_uname;  
        private EditText et_main_upass;  
      
        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
            et_main_uname = (EditText) findViewById(R.id.et_main_uname);  
            et_main_upass = (EditText) findViewById(R.id.et_main_upass);  
        }  
        public void operation(View view){  
            String uname=et_main_uname.getText().toString();  
            String upass=et_main_upass.getText().toString();  
      
            DBHelper dbHelper=new DBHelper(this,"G160618.db",null,2);  
            SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();  
            //添加1  
            for (int i = 0; i <100 ; i++) {  
                sqLiteDatabase.execSQL("insert into login(uname,upass) values('"+uname+i+"','"+upass+"')");  
            }  
            //添加2  
    //        ContentValues values=new ContentValues();  
    //        values.put("uname",uname);  
    //        values.put("upass",upass);  
    //        values.putNull("uid");  
    //        sqLiteDatabase.insert("login","uname",values);  
      
            //删除  
            //sqLiteDatabase.delete("login","uid=?",new String[]{102+""});  
      
            //修改  
    //        ContentValues values=new ContentValues();  
    //        values.put("uname",uname);  
    //        values.put("upass",upass);  
    //        sqLiteDatabase.update("login",values,"uid=?",new String[]{101+""});  
      
            //查询所有  
            int pageNo=2;    //第一页  
            int pageSize=5;  //每页5条  
            //minus  
    //        Cursor cursor=sqLiteDatabase.rawQuery("select * from login limit ?,?",new String[]{((pageNo-1)*pageSize)+"",pageSize+""});  
    //        while(cursor.moveToNext()){  
    //            int uid=cursor.getInt(cursor.getColumnIndex("uid"));  
    //            String name=cursor.getString(cursor.getColumnIndex("uname"));  
    //            String pass=cursor.getString(cursor.getColumnIndex("upass"));  
    //            Log.i("test",uid+" "+name+" "+pass);  
    //        }  
      
      
      
            Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();  
        }  
    }  




新建java MyProvider文件把内容提供出去
    package com.zking.administrator.g160618_android16_sqlite;  
      
    import android.content.ContentProvider;  
    import android.content.ContentValues;  
    import android.database.Cursor;  
    import android.database.sqlite.SQLiteDatabase;  
    import android.net.Uri;  
    import android.support.annotation.NonNull;  
    import android.support.annotation.Nullable;  
    import android.util.Log;  
      
    import com.zking.db.DBHelper;  
      
    /**  
     * Created by Administrator on 2017/7/17 0017.  
     */  
      
    public class MyProvider extends ContentProvider {  
        @Override  
        public boolean onCreate() {  
            Log.i("test","onCreate");  
            return false;  
        }  
      
        @Nullable  
        @Override  
        public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {  
            Log.i("test","query");  
      
            //把数据查询出来  
            DBHelper dbHelper=new DBHelper(getContext(),"G160618.db",null,2);  
            SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();  
            //sqLiteDatabase.rawQuery("select * from login",null);  
            return sqLiteDatabase.rawQuery("select * from login",null);  
        }  
      
        @Nullable  
        @Override  
        public String getType(@NonNull Uri uri) {  
            Log.i("test","getType");  
            return null;  
        }  
      
        @Nullable  
        @Override  
        public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {  
            Log.i("test","insert");  
            return null;  
        }  
      
        @Override  
        public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {  
            Log.i("test","delete");  
            return 0;  
        }  
      
        @Override  
        public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {  
            Log.i("test","update");  
            return 0;  
        }  
    }  



最后在xml里面对内容提供者进行配置,加上这样一句代码
 <!--配置内容提供者-->  
           <provider  
               android:authorities="com.zking.administrator.g160618_android16_sqlite.LOGIN"  
               android:name=".MyProvider"  
               android:exported="true"  
               ></provider>