All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.greenrobot.dao.query.CountQuery Maven / Gradle / Ivy

There is a newer version: 3.0.0-beta3
Show newest version
package de.greenrobot.dao.query;

import android.database.Cursor;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.DaoException;

public class CountQuery extends AbstractQuery {

    private final static class QueryData extends AbstractQueryData> {

        private QueryData(AbstractDao dao, String sql, String[] initialValues) {
            super(dao, sql, initialValues);
        }

        @Override
        protected CountQuery createQuery() {
            return new CountQuery(this, dao, sql, initialValues.clone());
        }
    }

    static  CountQuery create(AbstractDao dao, String sql, Object[] initialValues) {
        QueryData queryData = new QueryData(dao, sql, toStringArray(initialValues));
        return queryData.forCurrentThread();
    }

    private final QueryData queryData;

    private CountQuery(QueryData queryData, AbstractDao dao, String sql, String[] initialValues) {
        super(dao, sql, initialValues);
        this.queryData = queryData;
    }

    public CountQuery forCurrentThread() {
        return queryData.forCurrentThread(this);
    }

    /** Returns the count (number of results matching the query). Uses SELECT COUNT (*) sematics. */
    public long count() {
        checkThread();
        Cursor cursor = dao.getDatabase().rawQuery(sql, parameters);
        try {
            if (!cursor.moveToNext()) {
                throw new DaoException("No result for count");
            } else if (!cursor.isLast()) {
                throw new DaoException("Unexpected row count: " + cursor.getCount());
            } else if (cursor.getColumnCount() != 1) {
                throw new DaoException("Unexpected column count: " + cursor.getColumnCount());
            }
            return cursor.getLong(0);
        } finally {
            cursor.close();
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy