雖然自己寫的代碼也很糟糕,但還是能感覺到在Android開發方面的代碼比JEE的要亂很多
着重點不一樣吧
聯繫人修改
1、根據已有的數據,特別是id,查詢出要修改哪幾條數據,然後一條條去修改
這是一種方法,但我目前沒有采取這種方法,因爲服務器端返回的數據中只包含了一些數據,沒有很多像主鍵這樣的東西,所以我採取了另外一種寫法
2、刪除data表中有關的數據,然後再新增,這是我目前採用的方法,raw_contacts表和contacts表數據不刪除,只是修改
基本代碼類似下面
// 已知一個ID了,要修改他下面的數據
// 刪除他下面的DATA數據,然後再新增數據
long id = 3l;
// 根據id查詢出rawid
// 可能有多個rawid
Cursor cursor = rawContactsCursor(getApplicationContext(), id);
while (cursor.moveToNext()) {
long rawid = cursor.getLong(cursor
.getColumnIndex(RawContacts._ID));
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation
.newDelete(Data.CONTENT_URI).withSelection(
Data.RAW_CONTACT_ID + "=?",
new String[] { String.valueOf(rawid) })
.build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI).withValue(
Data.RAW_CONTACT_ID, rawid).withValues(
getNameNewCV()).build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI).withValue(
Data.RAW_CONTACT_ID, rawid).withValues(
getPhoneNewCV()).build());
try {
ContentProviderResult[] rst = getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
private Cursor rawContactsCursor(Context ctx, long id) {
return ctx.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI, null,
ContactsContract.RawContacts.CONTACT_ID + "=?",
new String[] { String.valueOf(id) }, null);
}
public ContentValues getNameNewCV() {
ContentValues cv = new ContentValues();
cv.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
cv.put(StructuredName.DISPLAY_NAME, "武 體");
cv.put(StructuredName.GIVEN_NAME, "體");
cv.put(StructuredName.FAMILY_NAME, "武");
return cv;
}
public ContentValues getPhoneNewCV() {
ContentValues cv = new ContentValues();
cv.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
cv.put(Phone.NUMBER, "666666");
cv.put(Phone.TYPE, Phone.TYPE_COMPANY_MAIN);
return cv;
}
備註:這樣修改還是有問題的,貌似contacts會生成新的記錄,這樣對於需要contact_id的情況就是悲劇啊
下面刪除聯繫人的代碼也還是有問題的
// 刪除聯繫人
// 刪除Data
long id = 1l;
// 根據id查詢出rawid
// 可能有多個rawid
Cursor cursor = rawContactsCursor(getApplicationContext(), id);
ArrayList<ContentProviderOperation> ops = null;
while (cursor.moveToNext()) {
long rawid = cursor.getLong(cursor
.getColumnIndex(RawContacts._ID));
ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation
.newDelete(Data.CONTENT_URI).withSelection(
Data.RAW_CONTACT_ID + "=?",
new String[] { String.valueOf(rawid) })
.build());
ops.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(RawContacts.CONTENT_URI,
rawid)).build());
ops.add(ContentProviderOperation.newDelete(
ContentUris
.withAppendedId(Contacts.CONTENT_URI, id))
.build());
try {
ContentProviderResult[] rst = getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}