ContentValues 和HashTable類似都是一種存儲的機制 但是兩者最大的區別就在於,contenvalues只能存儲基本類型的數據,像string,int之類的,不能存儲對象這種東西,而HashTable卻可以存儲對象。
在忘數據庫中插入數據的時候,首先應該有一個ContentValues的對象所以:
ContentValues initialValues = new ContentValues();
initialValues.put(key,values);
SQLiteDataBase sdb ;
sdb.insert(database_name,null,initialValues);
插入成功就返回記錄的id否則返回-1;
就可以插入一行數據,詳細見下面代碼
public Uri insert(Uri uri, ContentValues initialValues) { if (uriMatcher.match(uri) != CONTACTS) { throw new IllegalArgumentException("unknow uri " + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); System.out.println("contentValues插入成功,initailValues不是空的"); } else { values = new ContentValues(); } Long now = Long.valueOf(System.currentTimeMillis()); // 設置默認值 if (values.containsKey(ContactColumn.CREATED) == false) { values.put(ContactColumn.CREATED, now); } if (values.containsKey(ContactColumn.NAME) == false) { values.put(ContactColumn.NAME, now); } if (values.containsKey(ContactColumn.EMAIL) == false) { values.put(ContactColumn.EMAIL, now); } if (values.containsKey(ContactColumn.MOBILE) == false) { values.put(ContactColumn.MOBILE, now); } if (values.containsKey(ContactColumn.MODIFIED) == false) { values.put(ContactColumn.MODIFIED, now); } System.out.println("應該插入成功了吧"); long RowId = contactsDB.insert(CONTACTS_TABLE, null, values); if (RowId > 0) { Uri noteUri = ContentUris.withAppendedId(CONTENT_URI, RowId); getContext().getContentResolver().notifyChange(noteUri, null); System.out.println("到這里也是沒問題的!"); return noteUri; } throw new IllegalArgumentException("unknow uri " + uri); }
當然以上代碼是根據Uri來操作的所以要想明白代碼怎么回事?還要明白ContentProvider到底是怎么存儲數據的!