在一些应用中已经提供了内容提供者(比如短信、手机联系人)我们只需要创建内容解析者就可以对这些应用里面的数据进行操作
一、contentprovide
1.在清单文件中注册
<provider
android:name="com.guo.mycontentprovider.MyContentProvider"
android:authorities="guojiawei"
android:exported="true" >
</provider>
2.
public class MySQLiteDatabase extends SQLiteOpenHelper {
public MySQLiteDatabase(Context context) {
super(context, "contentprovider.db", null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table goods(id integer primary key autoincrement, name varchar(20), price varchar(20))");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
3.新建一个类继承contentprovide
private SQLiteDatabase db;
public boolean onCreate() {
MySQLiteDatabase mySQLiteDatabase = new MySQLiteDatabase(getContext());
//执行这个语句就会新建库,往库中插入数据,使用contentprovide将数据暴露到外面,使其他的应用可以访问
db = mySQLiteDatabase.getReadableDatabase();
return false;
}
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
return db.query("goods", projection, selection, selectionArgs, null,
null, null, null);
}
//
public String getType(Uri uri) {
return null;
}
/**
* Uri uri:用来连接 内容提供者和内容解析者(内容解析中通过uri找到内容提供者)
*
* 插入操作,具体的逻辑代码由方法体决定
* */
public Uri insert(Uri uri, ContentValues values) {
db.insert("goods", null, values);
return null;
}
public int delete(Uri uri, String selection, String[] selectionArgs) {
return db.delete("goods", selection, selectionArgs);
}
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return db.update("goods", values, selection, selectionArgs);
}
}
二、内容解析者
(通过URI找到内容提供者,一些应用的URI是写死的,直接拿来用就可以)
public class MainActivity extends Activity {
private int id;
private String name;
private String price;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取一个内容解析者对象
ContentResolver resolver = getContentResolver();
/**
*
* */
ContentValues values = new ContentValues();
// 插入数据
values.put("name", "kongtiao");
values.put("price", "1800");
// 将字符串转化为URI:parse()
// content://主机名
// resolver.insert(Uri.parse("content://guojiawei"), values);
// 删除数据
// resolver.delete(Uri.parse("content://guojiawei"), "id=?", new
// String[]{"3"});
// 更新数据
values.put("name", "彩电1");
// resolver.update(Uri.parse("content://guojiawei"), values, "id=?",new
// String[] {"2"});
// 查询数据
/**
* 参数一:uri 参数二:想要查询的数据(表中的字段) 参数三:查询的条件,如果为null,则表示没有查询条件的限制
* 参数四:补全查询条件里面的占位符 参数五:
*
* */
//有条件的查询
Cursor cursor = resolver.query(Uri.parse("content://guojiawei"), new String[]{"id","name","price"}, "id=?", new String[]{"1"}, null);
//无条件的查询
//Cursor cursor = resolver.query(Uri.parse("content://guojiawei"),new String[] { "id","name","price" }, null, null, null);
while (cursor.moveToNext()) {
id = cursor.getInt(cursor.getColumnIndex("id"));
name = cursor.getString(cursor.getColumnIndex("name"));
price = cursor.getString(0);
}
Log.i("myTag", id + "," + name + "," + price);
}
}