1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License 15 */ 16package com.android.providers.contacts; 17 18import android.content.ContentValues; 19import android.content.Context; 20import android.database.Cursor; 21import android.database.sqlite.SQLiteDatabase; 22import android.provider.ContactsContract.CommonDataKinds.BaseTypes; 23import android.text.TextUtils; 24 25/** 26 * Superclass for data row handlers that deal with types (e.g. Home, Work, Other) and 27 * labels, which are custom types. 28 */ 29public class DataRowHandlerForCommonDataKind extends DataRowHandler { 30 31 private final String mTypeColumn; 32 private final String mLabelColumn; 33 34 public DataRowHandlerForCommonDataKind(Context context, ContactsDatabaseHelper dbHelper, 35 ContactAggregator aggregator, String mimetype, String typeColumn, String labelColumn) { 36 super(context, dbHelper, aggregator, mimetype); 37 mTypeColumn = typeColumn; 38 mLabelColumn = labelColumn; 39 } 40 41 @Override 42 public long insert(SQLiteDatabase db, TransactionContext txContext, long rawContactId, 43 ContentValues values) { 44 enforceTypeAndLabel(values); 45 return super.insert(db, txContext, rawContactId, values); 46 } 47 48 @Override 49 public boolean update(SQLiteDatabase db, TransactionContext txContext, ContentValues values, 50 Cursor c, boolean callerIsSyncAdapter) { 51 final long dataId = c.getLong(DataUpdateQuery._ID); 52 final ContentValues augmented = getAugmentedValues(db, dataId, values); 53 if (augmented == null) { // No change 54 return false; 55 } 56 enforceTypeAndLabel(augmented); 57 return super.update(db, txContext, values, c, callerIsSyncAdapter); 58 } 59 60 /** 61 * If the given {@link ContentValues} defines {@link #mTypeColumn}, 62 * enforce that {@link #mLabelColumn} only appears when type is 63 * {@link BaseTypes#TYPE_CUSTOM}. Exception is thrown otherwise. 64 */ 65 private void enforceTypeAndLabel(ContentValues augmented) { 66 final boolean hasType = !TextUtils.isEmpty(augmented.getAsString(mTypeColumn)); 67 final boolean hasLabel = !TextUtils.isEmpty(augmented.getAsString(mLabelColumn)); 68 69 if (hasLabel && !hasType) { 70 // When label exists, assert that some type is defined 71 throw new IllegalArgumentException(mTypeColumn + " must be specified when " 72 + mLabelColumn + " is defined."); 73 } 74 } 75 76 @Override 77 public boolean hasSearchableData() { 78 return true; 79 } 80} 81