存储方式之ContentProvider
开始学习之前先回忆一下android的几种存储方式:
- SharedPreference
- ContentProvider
- SQLite数据库
- 文件存储
- sdCard存储
这几种是我记忆中的5中存储方式。最喜欢的也是用的最多的是SharedPreference简单方便。然后就是数据库,因为用的多,不得不喜欢呀。一直让我很纠结的就是今天学习的ContentProvider。原因?因为用的少呀(其实是没用过)。因为项目里不需要用,也就只是了解一下,没有去研究过,今天又时间,学习了一下,赶紧记录下来,好记性不如烂笔头呀!
ContentProvider的几个要点:
- 定义基本字段
- 在manifest里添加(provider和在需要用的activity里添加两个新的minetype)
- 继承ContentProvider
下面是代码:
1.定义基本字段
public class NotePad { public static final String AUTHORITY = "com.google.provider.NotePad"; //ContentProvider的uri public NotePad(){} //定义基本字段 public static final class Notes implements BaseColumns{ public Notes(){} //这里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 DESC"; //字段 public static final String TITLE = "title"; public static final String NOTE = "note"; public static final String CREATEDDATE = "created"; public static final String MODIFIEDDATE = "modified"; } }
2.在manifest里添加(provider和在需要用的activity里添加两个新的minetype)
<activity android:label="@string/app_name" android:name="contentPro.DataProviderActivity" > <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"/> </intent-filter> <intent-filter> <data android:mimeType="vnd.android.cursor.item/vnd.google.note"/> </intent-filter> </activity> <provider android:name="contentPro.NotePadProvider" android:authorities="com.google.provider.NotePad"/>
3.继承ContentProvider
public class NotePadProvider extends ContentProvider { private static final String TAG = "NotePadProvider"; // 数据库名 private static final String DATABASE_NAME = "note_pad.db"; private static final int DATABASE_VERSION = 2; // 表名 private static final String NOTES_TABLE_NAME = "notes"; private static HashMap<String, String> sNotesProjectionMap; private static final int NOTES = 1; private static final int NOTE_ID = 2; private static final UriMatcher sUriMatcher; private DatabaseHelper mOpenHelper; // 创建表SQL语句 private static final String CREATE_TABLE = "CREATE TABLE " + NOTES_TABLE_NAME + " (" + Notes._ID + " INTEGER PRIMARY KEY," + Notes.TITLE + " TEXT," + Notes.NOTE + " TEXT," + Notes.CREATEDDATE + " INTEGER," + Notes.MODIFIEDDATE + " INTEGER" + ");"; static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES); sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID); sNotesProjectionMap = new HashMap<String, String>(); sNotesProjectionMap.put(Notes._ID, Notes._ID); sNotesProjectionMap.put(Notes.TITLE, Notes.TITLE); sNotesProjectionMap.put(Notes.NOTE, Notes.NOTE); sNotesProjectionMap.put(Notes.CREATEDDATE, Notes.CREATEDDATE); sNotesProjectionMap.put(Notes.MODIFIEDDATE, Notes.MODIFIEDDATE); } 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); } // 更新数据库 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } } @Override public boolean onCreate() { mOpenHelper = new DatabaseHelper(getContext()); return true; } @Override // 查询操作 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); switch (sUriMatcher.match(uri)) { case NOTES: qb.setTables(NOTES_TABLE_NAME); qb.setProjectionMap(sNotesProjectionMap); break; case NOTE_ID: qb.setTables(NOTES_TABLE_NAME); qb.setProjectionMap(sNotesProjectionMap); qb.appendWhere(Notes._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } String orderBy; if (TextUtils.isEmpty(sortOrder)) { orderBy = NotePad.Notes.DEFAULT_SORT_ORDER; } else { orderBy = sortOrder; } SQLiteDatabase db = mOpenHelper.getReadableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override // 如果有自定义类型,必须实现该方法 public String getType(Uri uri) { switch (sUriMatcher.match(uri)) { case NOTES: return Notes.CONTENT_TYPE; case NOTE_ID: return Notes.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI " + uri); } } @Override // 插入数据库 public Uri insert(Uri uri, ContentValues initialValues) { if (sUriMatcher.match(uri) != NOTES) { throw new IllegalArgumentException("Unknown URI " + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } Long now = Long.valueOf(System.currentTimeMillis()); if (values.containsKey(NotePad.Notes.CREATEDDATE) == false) { values.put(NotePad.Notes.CREATEDDATE, now); } if (values.containsKey(NotePad.Notes.MODIFIEDDATE) == false) { values.put(NotePad.Notes.MODIFIEDDATE, now); } if (values.containsKey(NotePad.Notes.TITLE) == false) { Resources r = Resources.getSystem(); values.put(NotePad.Notes.TITLE, r.getString(android.R.string.untitled)); } if (values.containsKey(NotePad.Notes.NOTE) == false) { values.put(NotePad.Notes.NOTE, ""); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(NOTES_TABLE_NAME, Notes.NOTE, values); if (rowId > 0) { Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } throw new SQLException("Failed to insert row into " + uri); } @Override // 删除数据 public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; switch (sUriMatcher.match(uri)) { case NOTES: count = db.delete(NOTES_TABLE_NAME, where, whereArgs); break; case NOTE_ID: String noteId = uri.getPathSegments().get(1); count = db.delete(NOTES_TABLE_NAME, Notes._ID + "=" + noteId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override // 更新数据 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; switch (sUriMatcher.match(uri)) { case NOTES: count = db.update(NOTES_TABLE_NAME, values, where, whereArgs); break; case NOTE_ID: String noteId = uri.getPathSegments().get(1); count = db.update(NOTES_TABLE_NAME, values, Notes._ID + "=" + noteId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } }
4.应用
public class DataProviderActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //插入数据 ContentValues values = new ContentValues(); values.put(NotePad.Notes.TITLE, "title1"); values.put(NotePad.Notes.NOTE, "NoteNote1"); getContentResolver().insert(NotePad.Notes.CONTENT_URI, values); values.clear(); values.put(NotePad.Notes.TITLE, "title2"); values.put(NotePad.Notes.NOTE, "NoteNote2"); getContentResolver().insert(NotePad.Notes.CONTENT_URI, values); /* 显示 */ displayNote(); } private void displayNote() { // TODO Auto-generated method stub String columns[] = new String[]{ NotePad.Notes._ID, NotePad.Notes.TITLE, NotePad.Notes.NOTE, NotePad.Notes.CREATEDDATE, NotePad.Notes.MODIFIEDDATE }; Uri myUri = NotePad.Notes.CONTENT_URI; Cursor cursor = this.managedQuery(myUri, columns, null, null, null); if (cursor.moveToFirst()) { String id = null; String title = null; do{ id = cursor.getString(cursor.getColumnIndex(NotePad.Notes._ID)); title = cursor.getString(cursor.getColumnIndex(NotePad.Notes.TITLE)); Toast toast=Toast.makeText(this, "TITLE:"+id + "NOTE:" + title, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 40); toast.show(); }while(cursor.moveToNext()); } } }
以上代码来源:http://blog.csdn.net/yinyuan1987/article/details/6973074
感谢yinyuan1987 代码很易懂!