Android ContentProviders数据共享

1.创建Content Providers

package com.Aina.Android;

import android.net.Uri;
import android.provider.BaseColumns;

/**
* com.Aina.Android Pro_ContentProviders
*
* @author Aina.huang E-mail: 674023920@qq.com
* @version 创建时间:2010 Jul 1, 2010 11:26:31 AM 类说明
*/
public class NotePad {

// Content Providers的URI
public static final String AUTHORITY = "com.google.android.provider.notepad";

private NotePad() {

}

/**
* 定义基本字段
*
* @author Aina_hk
*
*/
public static final class Notes implements BaseColumns {
private Notes() {

}

public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/notes");
// 新的MIME类型-多个
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note";
// 新的MIME类型-单个
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note";
// 默认排序
public static final String DEFAULT_SORT_ORDER = "modified ASC";
// 字段
public static final String TITLE = "title";
public static final String NOTE = "note";
public static final String CREATEDDATE = "created";
public static final String MODIFIEDDATE = "modified";
}
}




package com.Aina.Android;

import java.util.HashMap;

import com.Aina.Android.NotePad.Notes;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;
import android.text.TextUtils;

/**
* com.Aina.Android Pro_ContentProviders
*
* @author Aina.huang E-mail: 674023920@qq.com
* @version 创建时间:2010 Jul 1, 2010 11:55:55 AM 类说明
*/
public class NotePadProvider extends ContentProvider {

public static final String DATABASE_NAME = "test.db";
public static final String TABLE_NAME = "notes";
public static final int VERSION = 1;
public static final int NOTES = 1;
public static final int NOTE_ID = 2;
public static HashMap<String, String> hm = null;
public static UriMatcher mUriMatcher = null;
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME
+ " (" + Notes._ID + " INTEGER PRIMARY KEY," + Notes.TITLE
+ " TEXT," + Notes.NOTE + " TEXT," + Notes.CREATEDDATE
+ " INTEGER," + Notes.MODIFIEDDATE + " INTEGER)";
private SQLiteDataHelper msdh = null;
static {
mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES);
mUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID);
hm = new HashMap<String, String>();
hm.put(Notes._ID, Notes._ID);
hm.put(Notes.TITLE, Notes.TITLE);
hm.put(Notes.NOTE, Notes.NOTE);
hm.put(Notes.CREATEDDATE, Notes.CREATEDDATE);
hm.put(Notes.MODIFIEDDATE, Notes.MODIFIEDDATE);
}

private static class SQLiteDataHelper extends SQLiteOpenHelper {

public SQLiteDataHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}

}

/**
* 删除
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = msdh.getWritableDatabase();
int num = 0;
switch (mUriMatcher.match(uri)) {
case NOTES:
num = db.delete(TABLE_NAME, selection, selectionArgs);
break;
case NOTE_ID:
num = db.delete(TABLE_NAME, Notes._ID
+ " = "
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection
+ ')' : ""), selectionArgs);
break;
default:
break;
}
this.getContext().getContentResolver().notifyChange(uri, null);
return num;
}

@Override
public String getType(Uri uri) {
String str = "";
switch (mUriMatcher.match(uri)) {
case NOTES:
str = Notes.CONTENT_TYPE;
break;
case NOTE_ID:
str = Notes.CONTENT_ITEM_TYPE;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
return str;
}

/**
* 插入
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
if (mUriMatcher.match(uri) != NOTES) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues cv = null;
if (values == null) {
cv = new ContentValues();
} else {
cv = new ContentValues(values);
}
long num = System.currentTimeMillis();
if (cv.containsKey(Notes.CREATEDDATE) == false) {
cv.put(Notes.CREATEDDATE, num);
}
if (cv.containsKey(Notes.MODIFIEDDATE) == false) {
cv.put(Notes.MODIFIEDDATE, num);
}
if (cv.containsKey(Notes.TITLE) == false) {
Resources r = Resources.getSystem();
cv.put(Notes.TITLE, r.getString(android.R.string.untitled));
}
if (cv.containsKey(Notes.NOTE) == false) {
cv.put(Notes.NOTE, "");
}
SQLiteDatabase db = msdh.getWritableDatabase();
long id = db.insertOrThrow(TABLE_NAME, Notes.NOTE, cv);
if (id > 0) {
Uri uri_new = ContentUris.withAppendedId(uri, id);
this.getContext().getContentResolver().notifyChange(uri_new, null);
return uri_new;
}
return null;
}

@Override
public boolean onCreate() {
msdh = new SQLiteDataHelper(this.getContext(), TABLE_NAME, null,
VERSION);
return true;
}

/**
* 查询
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch (mUriMatcher.match(uri)) {
case NOTES:
qb.setTables(TABLE_NAME);
qb.setProjectionMap(hm);
break;
case NOTE_ID:
qb.setTables(TABLE_NAME);
qb.setProjectionMap(hm);
qb.appendWhere(Notes._ID + " = " + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
String orderBy = "";
if (TextUtils.isEmpty(sortOrder)) {
orderBy = Notes.DEFAULT_SORT_ORDER;
} else {
orderBy = sortOrder;
}
SQLiteDatabase db = msdh.getReadableDatabase();
Cursor cursor = qb.query(db, projection, selection, selectionArgs,
null, null, orderBy);
cursor.setNotificationUri(this.getContext().getContentResolver(), uri);
return cursor;
}

/**
* 更新
*/
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = msdh.getWritableDatabase();
int num = 0;
switch (mUriMatcher.match(uri)) {
case NOTES:
num = db.update(TABLE_NAME, values, selection, selectionArgs);
break;
case NOTE_ID:
num = db.update(TABLE_NAME, values, Notes._ID
+ " = "
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(selection) ? " and (" + selection
+ ")" : ""), selectionArgs);
default:
break;
}
this.getContext().getContentResolver().notifyChange(uri, null);
return num;
}
}




package com.Aina.Android;

import com.Aina.Android.NotePad.Notes;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class Test extends Activity {
/** Called when the activity is first created. */
ListView lv = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) this.findViewById(R.id.ListView01);
ContentValues cv = new ContentValues();
cv.put(Notes.TITLE, "title1");
cv.put(Notes.NOTE, "note1");
this.getContentResolver().insert(Notes.CONTENT_URI, cv);
cv.clear();
cv.put(Notes.TITLE, "title2");
cv.put(Notes.NOTE, "note2");
this.getContentResolver().insert(Notes.CONTENT_URI, cv);
this.displayNote();
}

private void displayNote() {
String[] columns = new String[] { Notes._ID, Notes.TITLE, Notes.NOTE,
Notes.CREATEDDATE, Notes.MODIFIEDDATE };
Cursor c = this.managedQuery(Notes.CONTENT_URI, columns, null, null,
null);
this.startManagingCursor(c);
if (c != null) {
int cs = 0;

if(c.isBeforeFirst()){
cs++;
this.setTitle("isBeforeFirst"+cs);
}
if(c.moveToFirst()){
cs++;
this.setTitle("moveToFirst"+cs);
}
if(c.isFirst()){
cs++;
this.setTitle("isFirst"+cs);
}
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, c, new String[] {
Notes._ID, Notes.TITLE }, new int[] {
android.R.id.text1, android.R.id.text2 });
lv.setAdapter(adapter);

/*
* if (c.moveToFirst()) { this.setTitle(c.getCount()+""); String id =
* ""; String title = ""; do { id =
* c.getString(c.getColumnIndex(Notes._ID)); title =
* c.getString(c.getColumnIndex(Notes.TITLE)); Toast toast =
* Toast.makeText(this, c.getPosition()+"|ID:" + id + "|title:" +
* title, Toast.LENGTH_LONG); toast.show(); } while
* (c.moveToNext());
* }
*/
}
}
}



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Aina.Android" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<provider android:name=".NotePadProvider"
android:readPermission="android.permission.READ_CALENDAR"
android:writePermission="android.permission.WRITE_CALENDAR"
android:authorities="com.google.android.provider.notepad" />
<activity android:name=".Test"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<data
android:mimeType="vnd.android.cursor.dir/vnd.google.note">
</data>
</intent-filter>
<intent-filter>
<data
android:mimeType="vnd.android.cursor.item/vnd.google.note">
</data>
</intent-filter>
</activity>

</application>


</manifest>



2.通过ContentResolver来操作数据


package com.gn.provide;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class Tess extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String uri = "content://com.google.android.provider.notepad/xixi";
String[] columns = new String[] { "_id", "title", "note" };
try {
/*添加数据
ContentValues cv = new ContentValues();
cv.put("title", "new title");
cv.put("note", "new note");
this.getContentResolver().insert(Uri.parse(uri), cv);
*/
/*删除数据
int num = this.getContentResolver().delete(Uri.parse(uri), "title='new title'", null);
*/
/*修改
ContentValues cv = new ContentValues();
cv.put("title", "old title");
cv.put("note", "old note");
long num = this.getContentResolver().update(Uri.parse(uri), cv, "_id=3", null);
this.setTitle("num="+num);
*/
Cursor c = this
.managedQuery(Uri.parse(uri), null, null, null, null);
// Cursor c = this.getContentResolver().query(Uri.parse(uri),
// columns,
// null, null, null);
if (c == null) {
this.setTitle("c=null");
} else {
this.startManagingCursor(c);
ListView lv = (ListView) this.findViewById(R.id.ListView01);
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.simple, c, columns, new int[] { R.id.ID,
R.id.title, R.id.note });
lv.setAdapter(adapter);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}


}



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gn.provide"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.READ_CALENDAR"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Tess"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>


</manifest>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值