Android ContentProvider简单使用

来源:互联网 发布:美国网络言论自由吗 编辑:程序博客网 时间:2024/05/22 15:10

ContentProvider是允许不同应用进行数据交换的标准的API,ContentProvider以Uri的形式对外提供数据的访问操作接口,而其他应用则通过ContentResolver根据Uri去访问指定的数据。某个应用通过ContentProvider暴露了自己的数据接口,那么不管该应用程序是否启动,其他程序都可以通过该接口来操作自己的数据接口来操作其内部的数据,包括增加数据,删除数据,修改数据,查询数据等。

项目地址:http://download.csdn.net/download/weixin_40391500/10046744

数据使用SQLite存储

/** * Created by pc20170521 on 2017-10-25. */public class DataBaseHelper extends SQLiteOpenHelper {    private final static String name = "test.db";    private final static int version = 1;    private String test = "create table test_table(_id integer primary key autoincrement," +            "phone text)";    public DataBaseHelper(Context context) {        super(context, name, null, version);    }    @Override    public void onCreate(SQLiteDatabase db) {        db.execSQL(test);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    }}

操作数据

/** 插入 **/    public void insert(String phone) {        DataBaseHelper helper = new DataBaseHelper(mContext);        SQLiteDatabase db = helper.getWritableDatabase();        ContentValues contentValues = new ContentValues();        if (phone != null && !phone.isEmpty()){            contentValues.put("phone", phone);        }        db.insert("test_table", null, contentValues);        db.close();        helper.close();    }    /** 删除 **/    public void delete(String phone) {        DataBaseHelper helper = new DataBaseHelper(mContext);        SQLiteDatabase db = helper.getWritableDatabase();        db.execSQL("delete from test_table where phone = " + phone);        db.close();        helper.close();    }    /** 清空表数据 **/    public void clearTable() {        DataBaseHelper helper = new DataBaseHelper(mContext);        SQLiteDatabase db = helper.getWritableDatabase();        db.execSQL("DELETE FROM test_table");        db.close();        helper.close();    }    /** 删除表 **/    public void deleteTable() {        DataBaseHelper helper = new DataBaseHelper(mContext);        SQLiteDatabase db = helper.getWritableDatabase();        db.execSQL("DROP TABLE test_table");        db.close();        helper.close();    }    /** 修改 **/    public void update(Map<String,  String> map, String phone) {        DataBaseHelper helper = new DataBaseHelper(mContext);        SQLiteDatabase db = helper.getWritableDatabase();        ContentValues contentValues = new ContentValues();        if (map != null && !map.isEmpty()){            for (Map.Entry<String, String> entry : map.entrySet()) {                contentValues.put(entry.getKey(), entry.getValue());            }        }        String whereClause = "phone = ?";        String[] whereArgs={ phone };        db.update("test_table", contentValues, whereClause, whereArgs);        db.close();        helper.close();    }    /** 查询 **/    public ArrayList<String> selete() {        DataBaseHelper helper = new DataBaseHelper(mContext);        ArrayList<String> list = new ArrayList<>();        SQLiteDatabase db = helper.getWritableDatabase();        Cursor c = db.query("test_table",null,null,null,null,null,"_id desc");        while (c.moveToNext()){            list.add(c.getString(c.getColumnIndex("phone")));        }        c.close();        db.close();        helper.close();        return list;    }

ContentProvider对外提供数据的访问操作接口

/** * Created by pc20170521 on 2017-10-25. */public class ContentProviderUtils extends ContentProvider {    private DataBaseHelper helper = null;    private UriMatcher matcher = null;    @Override    public boolean onCreate() {        helper = new DataBaseHelper(getContext());        matcher = new UriMatcher(UriMatcher.NO_MATCH);        matcher.addURI("com.example.contentprovidertest", "test_table", 1);        // #匹配所有数字,*匹配所有字符        matcher.addURI("com.example.contentprovidertest", "test_table/#", 2);        return false;    }    @Nullable    @Override    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {        int code = matcher.match(uri);        Cursor cursor = null;        SQLiteDatabase db = helper.getWritableDatabase();        if (code == 1){            cursor = db.query("test_table", null, null, null, null, null, "_id desc");        }else if (code == 2){            long id = ContentUris.parseId(uri);            cursor = db.query("test_table", null, "_id=?", new String[]{String.valueOf(id)}, null, null, "_id desc");        }        return cursor;    }    @Nullable    @Override    public String getType(Uri uri) {        int code = matcher.match(uri);        String type = null;        if (code == 1){            type = "vnd.android.cursor.dir/test_table";//代表返回结果为多列数据        }else if (code == 2){            type = "vnd.android.cursor.item/test_table";//代表返回结果为单列数据        }        return type;    }    @Nullable    @Override    public Uri insert(Uri uri, ContentValues values) {        int code = matcher.match(uri);        if (code != 1 && code != 2) {            throw new RuntimeException("地址不能匹配");        }        SQLiteDatabase db = helper.getWritableDatabase();        long id = db.insert("test_table", null, values);        return ContentUris.withAppendedId(uri, id);// 返回值代表访问新添加数据的uri    }    @Override    public int delete(Uri uri, String selection, String[] selectionArgs) {        int code = matcher.match(uri);        if (code == 1) {            throw new RuntimeException("不能删除所有数据");        } else if (code == 2) {            long id = ContentUris.parseId(uri);            SQLiteDatabase db = helper.getWritableDatabase();            db.delete("test_table", "_id=?",                    new String[] { id + "" });        }        return 0;    }    @Override    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {        int code = matcher.match(uri);        int row = 0;        if (code == 2) {            long id = ContentUris.parseId(uri);            SQLiteDatabase db = helper.getWritableDatabase();            row = db.update("test_table", values, "_id=?",                    new String[] { id + "" });        }        return row;    }}

插入数据

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        PhoneData.getIntance(this).insert("10086");    }}<activity android:name=".MainActivity">    <intent-filter>        <action android:name="android.intent.action.MAIN" />        <category android:name="android.intent.category.LAUNCHER" />    </intent-filter></activity><provider    android:name=".utils.ContentProviderUtils"    android:authorities="com.example.contentprovidertest"    android:exported="true"></provider>

另一个应用调用ContentResolver获取数据

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        TextView tv = (TextView) findViewById(R.id.tv);        Uri uri = Uri.parse("content://com.example.contentprovidertest/test_table");        Cursor cursor = getContentResolver().query(uri, null, null, null, null);        String phone = "";        while (cursor.moveToNext()){            phone = cursor.getString(cursor.getColumnIndex("phone"));            Log.e("-----------", phone);        }        tv.setText(phone);    }}

项目地址:http://download.csdn.net/download/weixin_40391500/10046744

原创粉丝点击