一、ContentProvIDer保存数据介绍
一个程序可以通过实现一个ContentProvIDer的抽象接口将自己的数据完全暴露出去,而且ContentProvIDer是以类似数据库中表的方式将数据暴露的。那么外界获取其提供的数据,也就应该与从数据库中获取数据的 *** 作基本一样,只不过是采用URL来表示外界需要访问的“数据库”。
ContentProvIDer提供了一种多应用间数据共享的方式。
ContentProvIDer是个实现了一组用于提供其他应用程序存取数据的标准方法的类。应用程序可以在ContentProvIDer中执行如下 *** 作:查询数据、修改数据、添加数据、删除数据。
标准的ContentProvIDer:AndroID提供了一些已经在系统中实现的标准ContentProvIDer,比如联系人信息,图片库等等,可以用这些ContentProvIDer来访问设备上存储的联系人信息、图片等等。
在ContentProvIDer中使用的查询字符串有别于标准的SQL查询,很多诸如select、add、delete、modify等 *** 作都使用一种特殊的URL进行,这种URL由3部分组成,“content://”,代表数据的路径和一个可选的表示数据的ID。
content://media/internal/images 这个URL将返回设备上存储的所有图片
content://contacts/people/ 这个URL将返回设备上的所有联系人信息
content://contacts/people/45 这个URL返回单个结果(联系人信息中ID为45的联系人记录)
如果想要存储字节型数据,比如位图文件等,那保存该数据的数据列其实是一个表示实际保存保存文件的URL字符串,客户端通过它来读取对应的文件数据,处理这种数据类型的ContentProvIDer需要实现一个名为_data的字段,_data字段列出了该文件在AndroID文件系统上的精确路径。这个字段不仅是供客户端使用,而且也可以供ContentResolver使用。客户端可以调用ContentResolver.openOutputStream()方法来处理该URL指向的文件资源,如果是ContentResolver本身的话,由于其持有的权限比客户端要高,所以它能直接访问该数据文件。
二、使用方法
大多数ContentProvIDer使用AndroID文件系统或者sqlite数据库来保持数据,但是也可以以任何方式来存储。本例用sqlite数据库来保持数据。
1.创建一个接口,定义了一个名为CONTENT_URL,并且是public static final的Uri类型的类变量,必须为其指定一个唯一的字符串值,最好的方案是类的全称,和数据列的名称。
public interface IProivderMetaData { public static final String AUTHORITY = "com.zhangmiao.datastoragedemo"; public static final String DB_name = "book.db"; public static final int VERSION = 1; public interface BooktableMetaData extends BaseColumns { public static final String table_name = "book"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + table_name); public static final String BOOK_ID = "_ID"; public static final String BOOK_name = "name"; public static final String BOOK_PUBliSHER = "publisher"; public static final String SORT_ORDER = "_ID desc"; public static final String CONTENT_List = "vnd.androID.cursor.dir/vnd.bookprovIDer.book"; public static final String CONTENT_ITEM = "vnd.androID.cursor.item/vnd.bookprovIDer.book"; }}
2.实现sqliteOpenHelper
public class ContentProvIDerDBHelper extends sqliteOpenHelper implements IProivderMetaData { private static final String TAG = "ContentProvIDerDBHelper"; public ContentProvIDerDBHelper(Context context) { super(context,DB_name,null,VERSION); } @OverrIDe public voID onCreate(sqliteDatabase db) { ... } @OverrIDe public voID onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) { ... }}
3.创建一个继承了ContentProvIDer父类的类
public class ContentProvIDerDBHelper extends sqliteOpenHelper implements IProivderMetaData { public ContentProvIDerDBHelper(Context context) { super(context,int newVersion) { ... }}
4.在AndroIDManifest.xml中使用标签来设置调用ContentProvIDer。
<provIDer androID:authoritIEs="com.zhangmiao.datastoragedemo" androID:name=".BookContentProvIDer"/>
5.增加数据
mContentResolver = getContentResolver();String[] booknames = new String[]{"Chinese","Math","English","Sports"};String[] bookPublishers = new String[]{"XinHua","GongXin","DianZi","YouDian"};for (int i = 0; i < booknames.length; i++) { ContentValues values = new ContentValues(); values.put(IProivderMetaData.BooktableMetaData.BOOK_name,booknames[i]); values.put(IProivderMetaData.BooktableMetaData.BOOK_PUBliSHER,bookPublishers[i]); mContentResolver.insert(IProivderMetaData.BooktableMetaData.CONTENT_URI,values);}
6.删除数据
String bookID = "1";if (!"".equals(bookID)) { ContentValues values1 = new ContentValues(); values1.put(IProivderMetaData.BooktableMetaData.BOOK_ID,bookID); mContentResolver.delete(Uri.withAppendedpath( IProivderMetaData.BooktableMetaData.CONTENT_URI,bookID), "_ID = ?",new String[]{bookID} );} else { mContentResolver.delete( IProivderMetaData.BooktableMetaData.CONTENT_URI,null );}
7.查询数据
Cursor cursor = mContentResolver.query(IProivderMetaData.BooktableMetaData.CONTENT_URI,null);String text = "";if (cursor != null) { while (cursor.movetoNext()) { String bookIDText =cursor.getString(cursor.getColumnIndex(IProivderMetaData.BooktableMetaData.BOOK_ID)); String booknameText =cursor.getString(cursor.getColumnIndex(IProivderMetaData.BooktableMetaData.BOOK_name)); String bookPublisherText =cursor.getString(cursor.getColumnIndex(IProivderMetaData.BooktableMetaData.BOOK_PUBliSHER)); text += "ID = " + bookIDText + ",name = " + booknameText + ",publisher = " + bookPublisherText + "\n"; } cursor.close(); mtableInfo.setText(text);}
8.更新数据
String bookID1 = "2";String bookname = "Art";String bookPublisher = "TIEDao";ContentValues values2 = new ContentValues();values2.put(IProivderMetaData.BooktableMetaData.BOOK_name,bookname);values2.put(IProivderMetaData.BooktableMetaData.BOOK_PUBliSHER,bookPublisher);if ("".equals(bookID1)) { mContentResolver.update(IProivderMetaData.BooktableMetaData.CONTENT_URI,values2,null);} else { mContentResolver.update(Uri.withAppendedpath(IProivderMetaData.BooktableMetaData.CONTENT_URI,bookID1),"_ID = ? ",new String[]{bookID1} );}
三、小案例
1.添加strings.xml文件
<string name="content_provIDer">ContentProvIDer</string> <string name="add_data">增加数据</string> <string name="delete_data">删除数据</string> <string name="update_data">更改数据</string> <string name="query_data">查询数据</string>
2.修改activity_main.xml文件
<?xml version="1.0" enCoding="utf-8"?><androID.support.design.Widget.CoordinatorLayout 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:fitsSystemwindows="true" tools:context="com.zhangmiao.datastoragedemo.MainActivity"> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical"> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_gravity="center_horizontal" androID:text="@string/content_provIDer" /> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:layout_marginBottom="@dimen/fab_margin" androID:layout_margintop="@dimen/fab_margin" androID:orIEntation="horizontal"> <button androID:ID="@+ID/provIDer_add" androID:layout_wIDth="0dp" androID:layout_height="wrap_content" androID:layout_weight="1" androID:text="@string/add_data" /> <button androID:ID="@+ID/provIDer_delete" androID:layout_wIDth="0dp" androID:layout_height="wrap_content" androID:layout_weight="1" androID:text="@string/delete_data" /> <button androID:ID="@+ID/provIDer_update" androID:layout_wIDth="0dp" androID:layout_height="wrap_content" androID:layout_weight="1" androID:text="@string/update_data" /> <button androID:ID="@+ID/provIDer_query" androID:layout_wIDth="0dp" androID:layout_height="wrap_content" androID:layout_weight="1" androID:text="@string/query_data" /> </linearLayout> <TextVIEw androID:ID="@+ID/table_info" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:text="@string/app_name" /> </linearLayout></androID.support.design.Widget.CoordinatorLayout>
3.添加IProvIDerMetaData接口
package com.zhangmiao.datastoragedemo;import androID.net.Uri;import androID.provIDer.BaseColumns;/** * Created by zhangmiao on 2016/12/20. */public interface IProvIDerMetaData { public static final String AUTHORITY = "com.zhangmiao.datastoragedemo"; public static final String DB_name = "book.db"; public static final int VERSION = 1; public interface BooktableMetaData extends BaseColumns { public static final String table_name = "book"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + table_name); public static final String BOOK_ID = "_ID"; public static final String BOOK_name = "name"; public static final String BOOK_PUBliSHER = "publisher"; public static final String SORT_ORDER = "_ID desc"; public static final String CONTENT_List = "vnd.androID.cursor.dir/vnd.bookprovIDer.book"; public static final String CONTENT_ITEM = "vnd.androID.cursor.item/vnd.bookprovIDer.book"; }}
4.添加ContentProvIDerDBHelper类
package com.zhangmiao.datastoragedemo;import androID.content.Context;import androID.database.sqlite.sqliteDatabase;import androID.database.sqlite.sqliteOpenHelper;import androID.util.Log;/** * Created by zhangmiao on 2016/12/20. */public class ContentProvIDerDBHelper extends sqliteOpenHelper implements IProvIDerMetaData { private static final String TAG = "ContentProvIDerDBHelper"; public ContentProvIDerDBHelper(Context context) { super(context,VERSION); } @OverrIDe public voID onCreate(sqliteDatabase db) { String tablesql = "CREATE table IF NOT EXISTS " + BooktableMetaData.table_name + " (" + BooktableMetaData.BOOK_ID + " INTEGER PRIMARY KEY autoINCREMENT," + BooktableMetaData.BOOK_name + " VARCHAR," + BooktableMetaData.BOOK_PUBliSHER + " VARCHAR)"; db.execsql(tablesql); } @OverrIDe public voID onUpgrade(sqliteDatabase db,int newVersion) { Log.w(TAG,"Upgrading database from version " + oldVersion + "to" + newVersion + ",which will destroy all old data"); db.execsql("DROP table IF EXISTS " + DB_name); onCreate(db); }}
5.添加BookContentProvIDer类
package com.zhangmiao.datastoragedemo;import androID.content.ContentProvIDer;import androID.content.ContentUris;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;import androID.util.Log;/** * Created by zhangmiao on 2016/12/21. */public class BookContentProvIDer extends ContentProvIDer { private static final String TAG = "BookContentProvIDer"; private static UriMatcher uriMatcher = null; private static final int BOOKS = 1; private static final int BOOK = 2; private ContentProvIDerDBHelper dbHelper; private sqliteDatabase db; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(IProvIDerMetaData.AUTHORITY,IProvIDerMetaData.BooktableMetaData.table_name,BOOKS); uriMatcher.addURI(IProvIDerMetaData.AUTHORITY,IProvIDerMetaData.BooktableMetaData.table_name + "/#",BOOK); } @OverrIDe public boolean onCreate() { dbHelper = new ContentProvIDerDBHelper(getContext()); return (dbHelper == null) ? false : true; } @Nullable @OverrIDe public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case BOOKS: return IProvIDerMetaData.BooktableMetaData.CONTENT_List; case BOOK: return IProvIDerMetaData.BooktableMetaData.CONTENT_ITEM; default: throw new IllegalArgumentException("This is a unKNow Uri" + uri.toString()); } } @Nullable @OverrIDe public Uri insert(Uri uri,ContentValues values) { switch (uriMatcher.match(uri)) { case BOOKS: db = dbHelper.getWritableDatabase(); long rowID = db.insert( IProvIDerMetaData.BooktableMetaData.table_name,IProvIDerMetaData.BooktableMetaData.BOOK_ID,values); Uri insertUri = Uri.withAppendedpath(uri,"/" + rowID); Log.i(TAG,"insertUri:" + insertUri.toString()); getContext().getContentResolver().notifyChange(uri,null); return insertUri; case BOOK: default: throw new IllegalArgumentException("This is a unKNow Uri" + uri.toString()); } } @Nullable @OverrIDe public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder) { db = dbHelper.getReadableDatabase(); switch (uriMatcher.match(uri)) { case BOOKS: return db.query(IProvIDerMetaData.BooktableMetaData.table_name,projection,selection,selectionArgs,sortOrder); case BOOK: long ID = ContentUris.parseID(uri); String where = "_ID=" + ID; if (selection != null && !"".equals(selection)) { where = selection + " and " + where; } return db.query(IProvIDerMetaData.BooktableMetaData.table_name,where,sortOrder); default: throw new IllegalArgumentException("This is a unKNow Uri" + uri.toString()); } } @OverrIDe public int delete(Uri uri,String[] selectionArgs) { db = dbHelper.getWritableDatabase(); switch (uriMatcher.match(uri)) { case BOOKS: return db.delete(IProvIDerMetaData.BooktableMetaData.table_name,selectionArgs); case BOOK: long ID = ContentUris.parseID(uri); String where = "_ID=" + ID; if (selection != null && !"".equals(selection)) { where = selection + " and " + where; } return db.delete(IProvIDerMetaData.BooktableMetaData.table_name,selectionArgs); default: throw new IllegalArgumentException("This is a unKNow Uri" + uri.toString()); } } @OverrIDe public int update(Uri uri,ContentValues values,String[] selectionArgs) { db = dbHelper.getWritableDatabase(); switch (uriMatcher.match(uri)) { case BOOKS: return db.update(IProvIDerMetaData.BooktableMetaData.table_name,values,null); case BOOK: long ID = ContentUris.parseID(uri); String where = "_ID=" + ID; if (selection != null && !"".equals(selection)) { where = selection + " and " + where; } return db.update(IProvIDerMetaData.BooktableMetaData.table_name,selectionArgs); default: throw new IllegalArgumentException("This is a unKNow Uri" + uri.toString()); } }}
6.修改AndroIDManifest.xml文件
<provIDer androID:authoritIEs="com.zhangmiao.datastoragedemo" androID:name=".BookContentProvIDer"/>
7.修改MainActivity
package com.zhangmiao.datastoragedemo;import androID.content.ContentResolver;import androID.content.ContentValues;import androID.database.Cursor;import androID.net.*;import androID.os.Bundle;import androID.support.v7.app.AppCompatActivity;import androID.util.Log;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.TextVIEw;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity implements VIEw.OnClickListener {private ContentResolver mContentResolver; private BookContentProvIDer mBookContentProvIDer;private TextVIEw mtableInfo; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { Log.v("MainActivity","onCreate"); super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); button cpAdd = (button) findVIEwByID(R.ID.provIDer_add); button cpDelete = (button) findVIEwByID(R.ID.provIDer_delete); button cpupdate = (button) findVIEwByID(R.ID.provIDer_update); button cpquery = (button) findVIEwByID(R.ID.provIDer_query); mtableInfo = (TextVIEw) findVIEwByID(R.ID.table_info); cpAdd.setonClickListener(this); cpDelete.setonClickListener(this); cpquery.setonClickListener(this); cpupdate.setonClickListener(this); } @OverrIDe public voID onClick(VIEw v) { switch (v.getID()) {case R.ID.provIDer_add: mContentResolver = getContentResolver(); String[] booknames = new String[]{"Chinese","Sports"}; String[] bookPublishers = new String[]{"XinHua","YouDian"}; for (int i = 0; i < booknames.length; i++) { ContentValues values = new ContentValues(); values.put(IProvIDerMetaData.BooktableMetaData.BOOK_name,booknames[i]); values.put(IProvIDerMetaData.BooktableMetaData.BOOK_PUBliSHER,bookPublishers[i]); mContentResolver.insert(IProvIDerMetaData.BooktableMetaData.CONTENT_URI,values); } break; case R.ID.provIDer_delete: String bookID = "1"; if (!"".equals(bookID)) { ContentValues values1 = new ContentValues(); values1.put(IProvIDerMetaData.BooktableMetaData.BOOK_ID,bookID); mContentResolver.delete( Uri.withAppendedpath( IProvIDerMetaData.BooktableMetaData.CONTENT_URI,bookID ),"_ID = ?",new String[]{bookID} ); } else { mContentResolver.delete( IProvIDerMetaData.BooktableMetaData.CONTENT_URI,null ); } break; case R.ID.provIDer_query: Cursor cursor = mContentResolver.query(IProvIDerMetaData.BooktableMetaData.CONTENT_URI,null); String text = ""; if (cursor != null) { while (cursor.movetoNext()) { String bookIDText = cursor.getString(cursor.getColumnIndex(IProvIDerMetaData.BooktableMetaData.BOOK_ID)); String booknameText = cursor.getString(cursor.getColumnIndex(IProvIDerMetaData.BooktableMetaData.BOOK_name)); String bookPublisherText = cursor.getString(cursor.getColumnIndex(IProvIDerMetaData.BooktableMetaData.BOOK_PUBliSHER)); text += "ID = " + bookIDText + ",name = " + booknameText + ",publisher = " + bookPublisherText + "\n"; } cursor.close(); mtableInfo.setText(text); } break; case R.ID.provIDer_update: String bookID1 = "2"; String bookname = "Art"; String bookPublisher = "TIEDao"; ContentValues values2 = new ContentValues(); values2.put(IProvIDerMetaData.BooktableMetaData.BOOK_name,bookname); values2.put(IProvIDerMetaData.BooktableMetaData.BOOK_PUBliSHER,bookPublisher); if ("".equals(bookID1)) { mContentResolver.update( IProvIDerMetaData.BooktableMetaData.CONTENT_URI,null); } else { mContentResolver.update( Uri.withAppendedpath( IProvIDerMetaData.BooktableMetaData.CONTENT_URI,new String[]{bookID1}); } break;default: Log.v("MainActivity","default"); break; } }}总结
以上是内存溢出为你收集整理的Android开发教程之ContentProvider数据存储全部内容,希望文章能够帮你解决Android开发教程之ContentProvider数据存储所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)