Return the count of all records in a table matching a selection. - Android Database

Android examples for Database:Table Row Query

Description

Return the count of all records in a table matching a selection.

Demo Code


import java.util.ArrayList;
import java.util.Locale;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

public class Main{
    /**//from   w  ww.  j a  va2  s  .  c  o m
     * Return the count of all records in a table matching a selection.
     *
     * @param db The database containing the table to query.
     * @param tableName The table name to compile the query against.
     * @param selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will
     * return all rows for the given table.
     * @param selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the
     * selection. The values will be bound as Strings.
     * @return The number of records in the selection, or 0 if the table does not exist.
     */
    public static long safeQueryForCount(SQLiteDatabase db,
            String tableName, String selection, String[] selectionArgs) {
        try {
            return DatabaseUtils.queryNumEntries(db, tableName, selection,
                    selectionArgs);
        } catch (SQLiteException e) {
            e.printStackTrace();
            return 0;
        }
    }
}

Related Tutorials