内容提供器(二 - 跨程序数据共享)
2016-09-23 23:15
441 查看
知识点:
ContentResolver中的增删改查方法都是不接受表名参数的,而是用Uri代替,这个参数被称为内容Uri.(由权限+路径组成)
最标准的格式:
content://com.example.app.provider/table1
content://com.example.app.provider/table1/1
使用Uri.parse()方法,可以将上述字符串解析成Uri对象、
使用通配符分别匹配这两种格式的内容URI
规则:*:表示匹配任意长度的任意字符(查表)
#:表示匹配任意长度的数字(查行)
创建内容提供器的步骤
共重写6个方法:
1 onCreate() 2 query() 3 insert() 4 update() 5 delete()
6 getType()(根据传入的内容返回相应的MIME类型)
借助UriMatcher这个类可以实现匹配Uri的功能,根据传入的自定义代码,在传出,就可以匹配相应的增删改查CURD的操作。
实现 :修改之前的DataBasetest 作为数据共享的对象
主活动的布局
主活动
AndroidManifest
对数据操作重写的类
内容提供
用于查出或修改DataBaseTest共享的数据的app
注意Uri的匹配问题,很容易 出错
ContentResolver中的增删改查方法都是不接受表名参数的,而是用Uri代替,这个参数被称为内容Uri.(由权限+路径组成)
最标准的格式:
content://com.example.app.provider/table1
content://com.example.app.provider/table1/1
使用Uri.parse()方法,可以将上述字符串解析成Uri对象、
使用通配符分别匹配这两种格式的内容URI
规则:*:表示匹配任意长度的任意字符(查表)
#:表示匹配任意长度的数字(查行)
创建内容提供器的步骤
共重写6个方法:
1 onCreate() 2 query() 3 insert() 4 update() 5 delete()
6 getType()(根据传入的内容返回相应的MIME类型)
借助UriMatcher这个类可以实现匹配Uri的功能,根据传入的自定义代码,在传出,就可以匹配相应的增删改查CURD的操作。
实现 :修改之前的DataBasetest 作为数据共享的对象
主活动的布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Create database" android:id="@+id/create_database"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Add data" android:id="@+id/add_data"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="update_data" android:id="@+id/update_data"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Delete_data" android:id="@+id/Delete_data"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Select_data" android:id="@+id/Select_data"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/replace_data" android:text="Replace data"/> </LinearLayout>
主活动
package com.example.databasetest; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private MyDatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper = new MyDatabaseHelper(this , "BookStore.db" ,null ,2); Button addData = (Button) findViewById(R.id.add_data); addData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = dbHelper.getReadableDatabase(); ContentValues values = new ContentValues();//用于组装数据 values.put("name","The Da Vinci Code"); values.put("author","Dan Brown"); values.put("pages","454"); values.put("price","16.53"); db.insert("Book" , null , values);//第二个参数用于未指定添加数据的情况下为可为空的列赋值为null values.clear(); values.put("name","The Da Vinci Code1"); values.put("author","Dan Brown1"); values.put("pages","411"); values.put("price","16.53"); db.insert("Book" , null , values); } }); Button updateData = (Button) findViewById(R.id.update_data); updateData.setOnClickListener(new View.OnClickListener() { @Override 4000 public void onClick(View v) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("price" , 10.99); db.update("Book" ,values , "name = ?" ,new String[]{"The Da Vinci Code"}); } }); Button deleteButton = (Button) findViewById(R.id.Delete_data); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete("Book","pages > ?", new String[]{"450"}); } }); Button selectDatabase = (Button) findViewById(R.id.Select_data); selectDatabase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.query("Book" , null ,null, null,null,null,null); // // Uri uri = Uri.parse("content://com.example.databasetest.provider/book"); 与上方的方法相同 // Cursor cursor = getContentResolver().query(uri, null, null, // null, null); System.out.println(cursor); if (cursor.moveToFirst()){ do{ String name = cursor.getString(cursor.getColumnIndex("name")); String author = cursor.getString(cursor.getColumnIndex("author")); int pages = cursor.getInt(cursor.getColumnIndex("pages")); double price = cursor.getDouble(cursor.getColumnIndex("price")); Log.d("MainActicity" , name); Log.d("MainActicity" , author); Log.d("MainActicity" ,""+ pages); Log.d("MainActicity" ,""+ price); }while (cursor.moveToNext()); } cursor.close(); } }); Button replaceData = (Button) findViewById(R.id.replace_data); replaceData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = dbHelper.getWritableDatabase(); db.beginTransaction();//开启事务 try{ db.delete("Book",null,null); // if(true){//手动抛出一个异常 // throw new NullPointerException(); // } ContentValues values =new ContentValues(); values.put("name","The Da Vinci Code22"); values.put("author","Dan Brown221"); values.put("pages","411"); values.put("price","16.53"); db.insert("Book" , null , values); db.setTransactionSuccessful();//事务成功执行 }catch (Exception e){ e.printStackTrace(); }finally { db.endTransaction();//结束事务 } } }); Button createDatabase = (Button)findViewById(R.id.create_database); createDatabase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dbHelper.getWritableDatabase(); } }); } }
AndroidManifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.databasetest"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <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="com.example.databasetest.DatabaseProvider" android:authorities="com.example.databasetest.provider" android:exported="true"> </provider> </application> </manifest>
对数据操作重写的类
package com.example.databasetest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class MyDatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK ="create table Book(" +" id integer primary key autoincrement , author text , " +"price real, pages integer , name text" + " ,category_id integer )";//在版本2的基础上增加外键; public static final String CREATE_CATEGORY = "create table Category (" +"id integer primary key autoincrement," +"category_name text ," +"category_code integer)"; private Context mContext; public MyDatabaseHelper(Context context , String name , SQLiteDatabase.CursorFactory factory , int verson){//CursorFactory为查询数据时返回自定义的Cursor super(context , name , factory , verson); mContext = context ; } @Override public void onCreate(SQLiteDatabase db) { // Toast.makeText(mContext,"Create succeed" ,Toast.LENGTH_SHORT).show(); db.execSQL(CREATE_BOOK); db.execSQL(CREATE_CATEGORY); // Log.d("MyDatabaseHelper", CREATE_BOOK); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//对数据库进行升级 执行的条件是在创建时的版本号大于上一次的版本号 Log.d("MyDatabaseHelper","zhangyu"+ oldVersion); switch (oldVersion){ case 1:db.execSQL(CREATE_CATEGORY); case 2:db.execSQL("alter table Book add column category_id integer"); //Log.d("MyDatabaseHelper","zhangyu"+ oldVersion); default: } } }
内容提供
package com.example.databasetest; 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 yuwei on 2016/9/21. */ public class DatabaseProvider extends ContentProvider { public static final int BOOK_DIR = 0; public static final int BOOK_ITEM = 1; public static final int CATEGORY_DIR = 2; public static final int CATEGORY_ITEM = 3; public static final String AUTHORITY = "com.example.databasetest.provider"; private static UriMatcher uriMatcher; private MyDatabaseHelper databaseHelper; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(AUTHORITY,"book",BOOK_DIR); uriMatcher.addURI(AUTHORITY,"book/#",BOOK_ITEM); uriMatcher.addURI(AUTHORITY,"category",CATEGORY_DIR); uriMatcher.addURI(AUTHORITY,"category/#",CATEGORY_ITEM); } @Override public boolean onCreate() { databaseHelper = new MyDatabaseHelper(getContext() , "BookStore.db" ,null,2); return true; } @Nullable @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = da 10bef tabaseHelper.getReadableDatabase(); Cursor cursor = null ; switch (uriMatcher.match(uri)){ case BOOK_DIR: cursor = db.query("Book",projection,selection,selectionArgs,null,null,sortOrder); break; case BOOK_ITEM: String bookId = uri.getPathSegments().get(1);//将UIR权限之后的部分以/分开,并将结果放入一个字符串列表中,第0个位置是路径。1个位置是id cursor = db.query("Book",projection,"id= ?",new String[]{bookId},null,null,sortOrder); break; case CATEGORY_DIR: cursor = db.query("Category",projection,selection,selectionArgs,null,null,sortOrder); break; case CATEGORY_ITEM: String categoryId = uri.getPathSegments().get(1); cursor = db.query("Category",projection,"id= ?",new String[]{categoryId},null,null,sortOrder); default: break; } return cursor; } @Nullable @Override public Uri insert(Uri uri, ContentValues values) { // System.out.println(uri); // System.out.println(values ); SQLiteDatabase db = databaseHelper.getWritableDatabase(); Uri uriReturn = null; // System.out.println(uriMatcher.match(uri)); switch (uriMatcher.match(uri)) { case BOOK_DIR: case BOOK_ITEM: long newBookId = db.insert("Book", null, values); uriReturn = Uri.parse("content://" + AUTHORITY + "/book/" + newBookId); // System.out.println("张玉玮"); break; case CATEGORY_DIR: case CATEGORY_ITEM: long newCategoryId = db.insert("Category", null, values); uriReturn = Uri.parse("content://" + AUTHORITY + "/category/" + newCategoryId); break; default: break; } return uriReturn; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { System.out.println(uri); SQLiteDatabase db = databaseHelper.getWritableDatabase(); int updatedRows = 0; switch (uriMatcher.match(uri)){ case BOOK_DIR: updatedRows = db.update("Book" , values , selection ,selectionArgs); break; case BOOK_ITEM: System.out.println(uri); String bookId = uri.getPathSegments().get(1); updatedRows = db.update("Book",values,"id=?",new String[]{bookId}); break; case CATEGORY_DIR: updatedRows = db.update("Category" , values , selection ,selectionArgs); break; case CATEGORY_ITEM: String categoryId = uri.getPathSegments().get(1); updatedRows = db.update("Category" , values , "id=?" ,new String[]{categoryId}); default: break; } return updatedRows; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = databaseHelper.getWritableDatabase(); int deletedRows = 0; switch (uriMatcher.match(uri)){ case BOOK_DIR: deletedRows = db.delete("Book" , selection ,selectionArgs); break; case BOOK_ITEM: String bookId = uri.getPathSegments().get(1); deletedRows = db.delete("Book" , "id=?" ,new String[]{bookId}); break; case CATEGORY_DIR: deletedRows = db.delete("Category" , selection ,selectionArgs); break; case CATEGORY_ITEM: String categoeyId = uri.getPathSegments().get(1); deletedRows = db.delete("Category" , "id=?" ,new String[]{categoeyId}); break; default: break; } return deletedRows; } @Nullable @Override public String getType(Uri uri) { System.out.println("我是getType"); switch (uriMatcher.match(uri)) { case BOOK_DIR: return "vnd.android.cursor.dir/vnd.com.example.databasetest.provider.book"; case BOOK_ITEM: return "vnd.android.cursor.item/vnd.com.example.databasetest.provider.book"; case CATEGORY_DIR: return "vnd.android.cursor.dir/vnd.com.example.databasetest.provider.category"; case CATEGORY_ITEM: return "vnd.android.cursor.item/vnd.com.example.databasetest.provider.category"; } return null; } }
用于查出或修改DataBaseTest共享的数据的app
package com.example.providertest; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private String newId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button addData = (Button) findViewById(R.id.add_data); addData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("content://com.example.databasetest.provider/book"); ContentValues values = new ContentValues(); values.put("name","zhangyuwei"); values.put("author","zhnagyuw"); values.put("pages",400); values.put("price",22.85); System.out.println(uri); Uri newUri = getContentResolver().insert(uri , values); if(newUri == null){ System.out.println((1234)); } newId = newUri.getPathSegments().get(1);//用于后来的更新和删除的id 使用这样的方法只能获得一条id 也就是说只能删除最近一条插入的id } }); Button queryData = (Button) findViewById(R.id.query_data); queryData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("content://com.example.databasetest.provider/book"); Cursor cursor = getContentResolver().query(uri, null, null, null, null); if(cursor!=null){ while(cursor.moveToNext()){ String name = cursor.getString(cursor.getColumnIndex("name")); String author = cursor.getString(cursor.getColumnIndex("author")); int pages = cursor.getInt(cursor.getColumnIndex("pages")); double price = cursor.getDouble(cursor.getColumnIndex("price")); Log.d("MainActivity","book name is "+name); Log.d("MainActivity","book author is "+author); Log.d("MainActivity","book pages is "+pages); Log.d("MainActivity","book price is "+price); } } cursor.close(); } }); Button updataData =(Button) findViewById(R.id.updata_data); updataData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("content://com.example.databasetest.provider/book/"+newId); System.out.println(newId+""); ContentValues values = new ContentValues(); values.put("name","zhangyuwe1121312i"); values.put("author","zhnagy123123uw"); values.put("pages",4010); values.put("price",22.815); getContentResolver().update(uri , values , null ,null); } }); Button button = (Button)findViewById(R.id.delete_data); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("content://com.example.databasetest.provider/book/"+newId); getContentResolver().delete(uri,null,null); } }); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="addData" android:id="@+id/add_data" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="queryData" android:id="@+id/query_data" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/updata_data" android:text="updata_data" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="delete_data" android:id="@+id/delete_data" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> </LinearLayout>
注意Uri的匹配问题,很容易 出错
相关文章推荐
- Android学习第十天—跨程序共享数据(探究内容提供器)
- 第七章 跨程序共享数据-探究内容提供器
- 第一行代码 第7章 内容提供器 --实现跨程序数据共享
- 内容提供器(Content Provider)--跨程序共享数据
- 安卓跨程序共享数据:内容提供器Content Provider
- 跨程序共享数据,探究内容提供器
- 第二行代码学习笔记——第七章:跨程序共享数据——探究内容提供器
- 跨程序共享数据-探究内容提供器(contentprovider&contentResover)(Recycleview 实例)
- Android跨程序共享数据,探究内容提供器(进阶篇)
- 阅读郭林《第一行代码》的笔记——第7章 跨程序共享数据,探究内容提供器
- 跨程序共享数据,探究内容提供器
- 跨程序共享数据,探究内容提供器
- 七,跨程序共享数据——内容提供器
- 跨程序共享数据——内容提供器
- Android之 内容提供器(1)——使用内容提供器访问其它程序共享的数据
- Android跨程序共享数据,探究内容提供器
- 跨程序共享数据,内容提供器
- 【练习】内容提供器一、访问其他程序的数据
- Android之 内容提供器(2)——创建自己的内容提供器将数据共享出去
- 内容提供者(Content Provider)——跨程序共享数据