Android How to - Check if a given string exists in the specified table and column








The following code shows how to check if a given string exists in the specified table and column.

Example

import org.xmlpull.v1.XmlPullParser;
//from   w  ww. j  a v a 2s.co  m
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


public class DbUtils {

  private SQLiteDatabase mDb;
  private Context mContext;

  private static final String TAG = DbUtils.class.getSimpleName();


  /** Checks if a given string exists in the specified table and column **/
  public static boolean exists(SQLiteDatabase db, String table, String column, String toCheck) {
    String[] selectionArgs = new String[] { toCheck };
    Cursor cursor = db.rawQuery("SELECT 1 FROM " + table + " where " + column + "=?", selectionArgs);
    boolean exists = cursor.moveToFirst();
    cursor.close();
    return exists;
  }
}