Android四组件-ContentProvider

来源:互联网 发布:js trigger事件 编辑:程序博客网 时间:2024/06/06 00:54

一、ContentProvider–内容提供者
1、建立一个类继承抽象类ContentProvider,在类中对其可以完成数据的增、删、改、查。

import android.content.ContentProvider;import android.content.ContentValues;import android.content.UriMatcher;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.net.Uri;import android.support.annotation.Nullable;/** * Created by Administrator on 2016/10/9. */public class MyContentProvider extends ContentProvider {    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);    private static final int QUERYSUCCESS = 1;    private static final int INSERTSUCCESS = 2;    private static final int UPDATESUCCESS = 3;    private static final int DELETESUCCESS = 4;    MySqliteHelper helper;    static{        //  com.yingu.provider/query        //  com.yingu.provider  要和配置清单中的保持一致        sURIMatcher.addURI("com.yingu.provider","query",QUERYSUCCESS);        sURIMatcher.addURI("com.yingu.provider","insert",INSERTSUCCESS);        sURIMatcher.addURI("com.yingu.provider","update",UPDATESUCCESS);        sURIMatcher.addURI("com.yingu.provider","delete",DELETESUCCESS);    }    //当ContentProvider被创建时候被调用    @Override    public boolean onCreate() {        //初始化我们编写的OpenHelper        helper =new MySqliteHelper(getContext());        return false;    }    //根据Uri查询selection指定条件所匹配的全部记录    //并且可以指定查询那系列以什么方式排列    //此方法已开始对外暴露    @Nullable    @Override    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {        int code =sURIMatcher.match(uri);        if(code == QUERYSUCCESS){            //说明路径匹配成功            SQLiteDatabase db= helper.getWritableDatabase();            //获取Cursor            Cursor cursor = db.query("info",projection,selection,selectionArgs,null,null,sortOrder);            return  cursor;        }else{            throw new IllegalArgumentException("URI错误,请检查");        }    }    //返回当前Uri的MIME类型,如果URI对应的数据可能包含多条记录    //那么MIME类型字符串就是以vnd.android.dir/开头    //如果该URI对应的数据只有一条记录,那么MIME类型字符串就是以vnd.android.cursor.item/开头    @Nullable    @Override    public String getType(Uri uri) {        return null;    }    //根据Uri插入Value对应的数据    @Nullable    @Override    public Uri insert(Uri uri, ContentValues values) {        int code =sURIMatcher.match(uri);        if(code == INSERTSUCCESS){            //说明路径匹配成功            SQLiteDatabase db= helper.getWritableDatabase();            long insert = db.insert("info",null,values);            Uri uri2= Uri.parse("com.yingu.success"+insert);            // 该部分属于内容观察者的代码            if( insert >0){                getContext().getContentResolver().notifyChange(uri,null);            }            db.close();            return uri2;        }else{            throw new IllegalArgumentException("URI错误,请检查");        }    }    //根据Uri删除selection指定条件所匹配的全部记录    @Override    public int delete(Uri uri, String selection, String[] selectionArgs) {        int code =sURIMatcher.match(uri);        if(code == DELETESUCCESS){            //说明路径匹配成功            SQLiteDatabase db= helper.getWritableDatabase();            int delete=  db.delete("info",selection,selectionArgs);            return  delete;        }else{            throw new IllegalArgumentException("URI错误,请检查");        }    }    //根据Uri修改selection指定条件所匹配的全部记录    @Override    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {        int code =sURIMatcher.match(uri);        if(code == UPDATESUCCESS){            //说明路径匹配成功            SQLiteDatabase db= helper.getWritableDatabase();            int update=  db.update("info",values,selection,selectionArgs);            return  update;        }else{            throw new IllegalArgumentException("URI错误,请检查");        }    }}

2、需要在AndroidMainfest.xml文件中对ContentProvider完成注册

<provider            android:authorities="com.example.androidtest14"            android:name=".MyContentProvider"/>

PS:注册的authorities属性值是全局唯一的
3、什么是Uri
是指通用资源标志符
content://com.example.androidtest14/data/#
Uri可以分为四个部分
A(content://):前缀表明数据受控于一个内容提供者。它从不修改,也就是schema。
B(com.example.androidtest14):是指在AndroidMainfest.xml中注册的provider中的android:authorities属性所对应的(一般使用包名)。
C(/data):表示具体操作与那个条目。
D(/#):表示具体操作那个条目下的那条记录
4、UriMatcher类
UriMatcher.NO_MATCH表示不匹配任何路径的返回码

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

往UriMatcher类里添加一个拼凑的Uri
UriMatcher是一个Uri的容器,容器里包含着我们即将可能操作的Uri

sURIMatcher.addURI("com.example.androidtest14", "data", 1);

二、在外部操作获取ContentProvider的数据操作
1、ContentResolver:
-使用ContentResolver操作ContentProvider中的数据,可以进行添加,删,改,查操作。
-使用Activity提供的getContentResolver()方法获取ContentResolver对象。
-ContentResolver类提供了与ContentProvider相同签名的四个方法。

import android.content.ContentValues;import android.database.Cursor;import android.net.Uri;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    //insert    public void click1(View v){        Uri uri = Uri.parse("content://com.yingu.provider/insert");        ContentValues values =new ContentValues();        values.put("name","wangwu");        values.put("money","5000");        Uri uri2 = getContentResolver().insert(uri,values);        Toast.makeText(getApplicationContext(),"uri="+uri2,Toast.LENGTH_LONG).show();    }    //删除    public void click2(View v){        Uri uri = Uri.parse("content://com.yingu.provider/delete");        int delete = getContentResolver().delete(uri,"name = ?",new String[]{"wangwu"});        Toast.makeText(getApplicationContext(),"删除了"+delete+"条数据",Toast.LENGTH_LONG).show();    }    //update    public void click3(View v){        Uri uri = Uri.parse("content://com.yingu.provider/update");        ContentValues values =new ContentValues();        values.put("money","10000");        int update = getContentResolver().update(uri,values,"name = ?",new String[]{"wangwu"});        Toast.makeText(getApplicationContext(),"更新了"+update+"条数据",Toast.LENGTH_LONG).show();    }    //query    public void click4(View v){        //方案一        /*SQLiteDatabase db= SQLiteDatabase.openDatabase("/data/data/com.z.androidday14/databases/Account.db",null,SQLiteDatabase.OPEN_READWRITE);        Cursor cursor =db.query("info",null,null,null,null,null,null);        String content="";        if(cursor!=null && cursor.getCount()>0){            while(cursor.moveToNext()){                String name= cursor.getString(1);                String money= cursor.getString(2);                content+="name="+name+",money="+money;            }            cursor.close();            ((TextView)findViewById(R.id.showText)).setText(content);        }*/        Uri uri = Uri.parse("content://com.yingu.provider/query");        Cursor cursor =getContentResolver().query(uri,new String[]{"name","money"},null,null,null);        String content="";        if(cursor!=null && cursor.getCount()>0){            while(cursor.moveToNext()){                String name= cursor.getString(0);                String money= cursor.getString(1);                content+="name="+name+",money="+money;            }            cursor.close();            ((TextView)findViewById(R.id.showText)).setText(content);        }    }}
0 0