ContentProvider
2015-06-11 10:57
561 查看
1、数据模型:每条数据都包含一个数值型的ID 字段,他用于在表格中唯一标识该记录。注意一定要有 (下划线 ) 。
2、URI用法:content://cm.example.myContentprovider/database/001
`
`
3、预定义ContentProvider:Android为当前平台提供的ContentProvider定义了CONTENT_URI常量。即调用以下预定义的ContentProvider时使用XXX.CONTENT_URI,如:Contacts.CONTENT_URI。
`
`
4、查询数据:
`
6、自定义ContentProvider:
`
`
2、URI用法:content://cm.example.myContentprovider/database/001
`
-content://:标准的前缀,用于表示该数据由ContentProvider管理。不能修改; -cm.example.myContentprovider:URI的authority部分,他标识该ContentProvider。对于第三方应用,改部分是完整的类名(使用小写的形式)来保证唯一性。在配置文件中的<provider>元素的authorities属性中声明authority; -database:ContentProvider路径部分,用于决定哪类数据被请求。如果ContentProvider仅提供一种数据类型,这部分可以没有;如果提供几种类型,包括子类型,这部分可以由几部分组成。 -001:被请求的特定的ID值。这是被请求记录的_ID值。如果请求不限于单条记录,则该部分及前面的斜线应该删除。
`
3、预定义ContentProvider:Android为当前平台提供的ContentProvider定义了CONTENT_URI常量。即调用以下预定义的ContentProvider时使用XXX.CONTENT_URI,如:Contacts.CONTENT_URI。
`
-Browser:读取或修改书签、浏览历史或网络搜索。 -CallLog:查看或更新通话历史。 -Contacts:获取、修改或保存联系人信息。 -LiveFolders:有ContentProvider提供内容的特定文件夹。 -MediaStore:访问视频、声音和图片。 -Setting:查看和获取蓝牙设置、铃声和其他设备偏好。 -SearchRecentSuggestions:该类能为应用程序创建简单的查询建议提供者,她基于近期查询提供建议。 -SyncStateContract:用于使用数据数组账号关联数据的ContentProvider约束,希望使用标准方式保存数据的provider可以使用它。 -UserDictionary:在可预测文本输入时,提供用户定义的单词给输入法使用,应用程序和输入法能增加数据到该字典,单词能关联频率信息和本地化信息。
`
4、查询数据:
` -ContentResolver.query():返回的Cursor对象的生命周期由程序员自己管理; -Activity.managedQuery():返回的Cursor对象的生命周期让Activity管理。
5、数据修改:
-增加记录:ContentResolver.insert(); -更新数据:ContentResolver.update(); -删除数据:ContentResolver.delete();
`
6、自定义ContentProvider:
`
-建立数据存储系统:可以使用文件存储方法或者SQLite数据库保存数据等其他任何方式。Android提供SQLiteOpenHelper类创建数据库及SQLiteDatabase类管理数据库。 -继承ContentProvider类提供访问数据方式。 -配置文件中声明ContentProvider: <provider android:name=".MyContentProvider" android:authorities="cm.example.android5module_contentprovider.mycontentprovider" android:exported="true" > </provider>
6、MainActivity代码如下:
import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) this.findViewById(R.id.textview); //插入数据 ContentValues vl = new ContentValues(); vl.put("username", "lichao"); vl.put("password", "123chao"); ContentResolver resolver = this.getContentResolver(); // Uri uri = resolver.insert(MyContentProvider.CONTENT_URI, vl); Uri uri = Uri.parse("content://cm.example.android5module_contentprovider.mycontentprovider/users"); resolver.insert(uri, vl); Cursor cursor = resolver.query(uri, new String[]{"username","password"},null ,null, null); while(cursor.moveToNext()){ String username = cursor.getString(cursor.getColumnIndexOrThrow("username")); String password = cursor.getString(cursor.getColumnIndexOrThrow("password")); tv.append(username+"-------"+password); } // if(cursor != null && cursor.moveToFirst()){ // String username = cursor.getString(cursor.getColumnIndexOrThrow("username")); // String password = cursor.getString(cursor.getColumnIndexOrThrow("password")); // tv.append(username+"-------"+password); // } // } }
7、MyContentProvider代码如下:
import android.animation.ArgbEvaluator; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; public class MyContentProvider extends ContentProvider { static final String DATABASE_NAME = "databastorage"; static final int DATABASE_VERSION = 1; static final String TABLE_NAME = "user"; static final String ID = "_id"; static final String USERNAME = "username"; static final String PASSWORD = "password"; static final String PROVIDER_NAME = "cm.example.android5module_contentprovider.mycontentprovider"; static final Uri CONTENT_URI = Uri.parse("content://"+PROVIDER_NAME+"/users"); static final int PERSONS = 1; static final int PERSONS_ID = 2; private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static{ uriMatcher.addURI(PROVIDER_NAME,"users",PERSONS); uriMatcher.addURI(PROVIDER_NAME, "users/#", PERSONS_ID); } DatabaseHelper dbHelper; //内部类,也可设置为外部类。 private static class DatabaseHelper extends SQLiteOpenHelper{ public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY," + USERNAME + " TEXT," + PASSWORD + " INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME); onCreate(db); } } @Override public boolean onCreate() { Context context = getContext(); dbHelper = new DatabaseHelper(context); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder(); sqlBuilder.setTables(TABLE_NAME); if(uriMatcher.match(uri) == PERSONS_ID){ sqlBuilder.appendWhere(ID+"="+uri.getPathSegments().get(1)); } SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor c= sqlBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(),uri); return c; } @Override public String getType(Uri uri) { switch(uriMatcher.match(uri)){ case PERSONS: return "vnd.android.cursor.dir/vnd.example.android5module_contentprovider"; case PERSONS_ID: return "vnd.android.cursor.item/vnd.example.android5module_contentprovider"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { //---add a new book--- if (uriMatcher.match(uri) != PERSONS) { throw new IllegalArgumentException("Unknown URI " + uri); } ContentValues val; if (values != null) { val = new ContentValues(values); } else { val = new ContentValues(); } if (val.containsKey(USERNAME) == false) { val.put(USERNAME, ""); } if (val.containsKey(PASSWORD) == false) { val.put(PASSWORD, 0); } SQLiteDatabase db = dbHelper.getWritableDatabase(); long rowID = db.insert(TABLE_NAME,USERNAME,val ); //---if added successfully--- if (rowID>0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(_uri, null); return _uri; } throw new SQLException("Failed to insert row into " + uri); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); int count = 0; switch(uriMatcher.match(uri)){ case PERSONS: count = db.delete(TABLE_NAME,selection, selectionArgs); break; case PERSONS_ID: String id = uri.getPathSegments().get(1); count = db.delete(TABLE_NAME, ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); int count = 0; switch (uriMatcher.match(uri)){ case PERSONS: count = db.update( TABLE_NAME, values, selection, selectionArgs); break; case PERSONS_ID: String id = uri.getPathSegments().get(1); count = db.update( TABLE_NAME, values, ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } }
8、activity_main.xml代码如下:
<RelativeLayout 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" tools:context="${relativePackage}.${activityClass}" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:id="@+id/textview" /> </RelativeLayout>
`
相关文章推荐
- setprecision(int n)等格式函数用法
- setprecision(int n)等格式函数用法 分类: POJ 2015-06-11 10:56 17人阅读 评论(0) 收藏
- PHP设计模式——职责链模式
- vsftp
- laravel5.0升级到5.1
- PHP设计模式——访问者模式
- wampserver安装之后连接phpMyAdmin 不成功的解决方法
- PHP生成不重复随机数的方法汇总
- 向数组中循环添加内容
- Sublime报Decode error - output not utf-8 or cp936 错误的解决办法
- CGI与fast-CGI的区别
- phpMyadmin
- Thinkphp入门 四 —布局、缓存、系统变量 (48)
- php5.3增加sqlserver2008的支持
- php 页面参数过多时自动拼接get参数的函数
- PHP整合PayPal支付
- php sortable 动态排序
- js传递二维数组给php
- php动态生成一个xml文件供swf调用
- FragmentPagerAdapter与FragmentStatePagerAdapter区别