广大博友,看过后帮忙顶顶,谢谢大家!!!
转载请注明:http://blog.csdn.net/richway2010/article/details/6600835
【博主:各位博友,网友们,大家网上好!欢迎光临本博客。 欢迎多多交流,多提意见,互相学习,互相进步,我们的口号是:好好学习,天天向上。】
Content Provider 属于Android应用程序的组件之一,作为应用程序之间唯一的共享数据的途径,Content Provider 主要的功能就是存储并检索数据以及向其他应用程序提供访问数据的借口。
Android 系统为一些常见的数据类型(如音乐、视频、图像、手机通信录联系人信息等)内置了一系列的 Content Provider, 这些都位于android.provider包下。持有特定的许可,可以在自己开发的应用程序中访问这些Content Provider。让自己的数据和其他应用程序共享有两种方式:创建自己的Content Provier(即继承自ContentProvider的子类) 或者是将自己的数据添加到已有的Content Provider中去,后者需要保证现有的Content Provider和自己的数据类型相同且具有该 Content Provider的写入权限。对于Content Provider,最重要的就是数据模型(data model) 和 URI。
创建自己的Content Provier主要分为以下几步:
1、创建Content Provier并应用SQLite存储系统
package org.guocheng.act;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
public class MyContentProvider extends ContentProvider {
private SQLiteDatabase sqlDB;
private DatabaseHelper dbHelper;
private static final String DATABASE_NAME = "Users.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "User";
private static final String TAG = "MyContentProvider";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建用于存储数据的表
db.execSQL("Create table " + TABLE_NAME + "( _id INTEGER PRIMARY KEY AUTOINCREMENT, USER_NAME TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
@Override
public int delete(Uri uri, String s, String[] as) {
return 0;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues contentvalues) {
sqlDB = dbHelper.getWritableDatabase();
long rowId = sqlDB.insert(TABLE_NAME, "", contentvalues);
if (rowId > 0) {
Uri rowUri = ContentUris.appendId(MyUsers.User.CONTENT_URI.buildUpon(), rowId).build();
getContext().getContentResolver().notifyChange(rowUri, null);
return rowUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
return (dbHelper == null) ? false : true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
SQLiteDatabase db = dbHelper.getReadableDatabase();
qb.setTables(TABLE_NAME);
Cursor c = qb.query(db, projection, selection, null, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
return 0;
}
}
2、定义URI及字段
package org.guocheng.act;
import android.net.Uri;
import android.provider.BaseColumns;
public class MyUsers {
public static final String AUTHORITY = "org.guocheng.act.MyContentProvider";
// BaseColumn类中已经包含了 _id字段
public static final class User implements BaseColumns {
public static final Uri CONTENT_URI = Uri.parse("content://org.guocheng.act.MyContentProvider");
// 表数据列
public static final String USER_NAME = "USER_NAME";
}
}
3、建立activity,生成数据,查询数据并以listview展现
package org.guocheng.act;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ContentProviderTestActivity extends Activity {
ListView lv ;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
insertRecord("MyUsers");
displayRecords();
}
private void insertRecord(String userName) {
ContentValues values = new ContentValues();
values.put(MyUsers.User.USER_NAME, userName);
getContentResolver().insert(MyUsers.User.CONTENT_URI, values);
}
private void displayRecords() {
String columns[] = new String[] { MyUsers.User._ID, MyUsers.User.USER_NAME };
Uri myUri = MyUsers.User.CONTENT_URI;
Cursor cur = managedQuery(myUri, columns,null, null, null );
List<String> ls = new ArrayList<String>();
if (cur.moveToFirst()) {
for (int i = 0; i < cur.getCount(); i++) {
String name = cur.getString(1);
ls.add(name);
cur.moveToNext();
}
}
lv = (ListView)findViewById(R.id.lis);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ls));
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/lis" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:paddingLeft="20px">
</ListView>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.guocheng.act"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ContentProviderTestActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:name="MyContentProvider" android:authorities="org.guocheng.act.MyContentProvider" />
</application>
</manifest>
所有代码结束。
运行效果图:
OK,这就是自定义的Content Provider.希望对你有所帮助。