Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of 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,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License
     15  */
     16 
     17 package com.android.providers.contacts.util;
     18 
     19 import android.text.TextUtils;
     20 
     21 import java.util.ArrayList;
     22 import java.util.List;
     23 
     24 /**
     25  * Builds a selection clause by concatenating several clauses with AND.
     26  */
     27 public class SelectionBuilder {
     28     private static final String[] EMPTY_STRING_ARRAY =  new String[0];
     29     private final List<String> mWhereClauses;
     30 
     31     /**
     32      * @param baseSelection The base selection to start with. This is typically
     33      *      the user supplied selection arg. Pass null if no base selection is
     34      *      required.
     35      */
     36     public SelectionBuilder(String baseSelection) {
     37         mWhereClauses = new ArrayList<String>();
     38         addClause(baseSelection);
     39     }
     40 
     41     /**
     42      * Adds a new clause to the selection. Nothing is added if the supplied clause
     43      * is null or empty.
     44      */
     45     public SelectionBuilder addClause(String clause) {
     46         if (!TextUtils.isEmpty(clause)) {
     47             mWhereClauses.add(clause);
     48         }
     49         return this;
     50     }
     51 
     52     /**
     53      * Returns a combined selection clause with AND of all clauses added using
     54      * {@link #addClause(String)}. Returns null if no clause has been added or
     55      * only null/empty clauses have been added till now.
     56      */
     57     public String build() {
     58         if (mWhereClauses.size() == 0) {
     59             return null;
     60         }
     61         return DbQueryUtils.concatenateClauses(mWhereClauses.toArray(EMPTY_STRING_ARRAY));
     62     }
     63 }
     64