private boolean initialize() { mContext = getContext(); mContentResolver = mContext.getContentResolver(); mOpenHelper = DatabaseHelper.getInstance(mContext); try { mDb = mOpenHelper.getWritableDatabase(); } catch (SQLiteException ex) { mDb = mOpenHelper.getReadableDatabase(); } return true; }
@SuppressLint("SimpleDateFormat") @Override public Uri insert(Uri uri, ContentValues values) { // TODO Auto-generated method stub // 新增,故uri只能为collection if (sUriMatch.match(uri) != HISTORY_COLLECTION_URI_INDICATOR) { throw new IllegalArgumentException("URI =" + uri); } // 允许插入空行 ContentValues cv; if (values == null) { cv = new ContentValues(); } else { cv = new ContentValues(values); } // if (cv.containsKey(ChatHistoryTable.CHAT_TIME)) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd-HH:mm:ss"); String now = sdf.format(new Date(System.currentTimeMillis())); cv.put(ChatHistoryTable.CHAT_TIME, now); } mDb = mOpenHelper.getWritableDatabase(); long rowId = mDb.insert(ChatHistoryTable.TABLE_NAME, null, cv); if (rowId > 0) { Uri insertUri = ContentUris.withAppendedId(ChatHistoryTable.CONTENT_URI, rowId); mContentResolver.notifyChange(insertUri, null); return insertUri; } throw new SQLiteException("Failed to insert!!!"); }
@Override public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // TODO Auto-generated method stub // check uri // first 通过SQLiteQueryBuilder,设置数据库查询的信息.Uri有两种情况,一种是collect, // 一种已经指定某个item,两者需要区别对待,item将获取_ID,并在where中增加一个匹配条件. SQLiteQueryBuilder dbQuery = new SQLiteQueryBuilder(); final int match = sUriMatch.match(uri); switch (match) { case HISTORY_COLLECTION_URI_INDICATOR: dbQuery.setTables(ChatHistoryTable.TABLE_NAME); dbQuery.setProjectionMap(sHistoryProjectionMap); break; case HISTORY_ITEM_URI_INDICATION: dbQuery.setTables(ChatHistoryTable.TABLE_NAME); dbQuery.setProjectionMap(sHistoryProjectionMap); dbQuery.appendWhere(ChatHistoryTable._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknow uri=" + uri); } // second v 对排序进行缺省设置 // String order = TextUtils.isEmpty(sortOrder) ? HistoryTable.DEFAULE_SORT_ORDER : sortOrder; SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // third start query final Cursor c = dbQuery.query(db, projection, selection, selectionArgs, null, null, sortOrder); // fourth 向系统注册通知:观察所要查询的数据,即Uri对应的数据是否发生变化 // 开发者通过provider接口获取数据,可通过通知获知数据已经发生变更 if (c != null) { c.setNotificationUri(mContentResolver, ChatHistoryTable.CONTENT_URI); } return c; }