Java Code Examples for com.j256.ormlite.stmt.PreparedQuery

The following are top voted examples for showing how to use com.j256.ormlite.stmt.PreparedQuery. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: BachelorPraktikum   File: VaultDao.java   Source Code and License 7 votes vote down vote up
/**
 * This is used to query a single Event ({@link VaultEntry} before a given point in time.
 * This is useful to determine why certain events might have happened (correlation of events).
 *
 * @param timestamp The point in time to get the preceding event from.
 * @param type The Type of {@link VaultEntry} to query for.
 * @return The event of the {@link VaultEntryType} preceding the specified point in time.
 */
public VaultEntry queryLatestEventBefore(final Date timestamp, final VaultEntryType type) {
    VaultEntry returnValue = null;
    try {

        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", false)
                .limit(1L)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, type)
                .and()
                .le(VaultEntry.TIMESTAMP_FIELD_NAME, timestamp)
                .prepare();
        List<VaultEntry> tmpList = vaultDao.query(query);
        if (tmpList.size() > 0) {
            returnValue = tmpList.get(0);
        }
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
    }
    return returnValue;
}
 
Example 2
Project: OpenDiabetes   File: VaultDao.java   Source Code and License 6 votes vote down vote up
public List<VaultEntry> queryGlucoseBetween(Date from, Date to) {
    List<VaultEntry> returnValues = null;
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_BG)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_CGM)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_CGM_ALERT)
                .and()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, from, to)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, "Error while db query", ex);
    }
    return returnValues;
}
 
Example 3
Project: OpenDiabetes   File: VaultDao.java   Source Code and License 6 votes vote down vote up
public List<VaultEntry> queryExerciseBetween(Date from, Date to) {
    List<VaultEntry> returnValues = null;
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.EXERCISE_BICYCLE)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.EXERCISE_RUN)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.EXERCISE_WALK)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.EXERCISE_MANUAL)
                .and()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, from, to)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, "Error while db query", ex);
    }
    return returnValues;
}
 
Example 4
Project: OpenDiabetes   File: VaultDao.java   Source Code and License 6 votes vote down vote up
public VaultEntry queryLatestEventBefore(Date timestamp, VaultEntryType type) {
    VaultEntry returnValue = null;
    try {

        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", false)
                .limit(1L)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, type)
                .and()
                .le(VaultEntry.TIMESTAMP_FIELD_NAME, timestamp)
                .prepare();
        List<VaultEntry> tmpList = vaultDao.query(query);
        if (tmpList.size() > 0) {
            returnValue = tmpList.get(0);
        }
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, "Error while db query", ex);
    }
    return returnValue;
}
 
Example 5
Project: OpenDiabetes   File: VaultDao.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param id
 * @return vault entry with respective id or null
 */
public VaultEntry queryVaultEntryById(long id) {
    List<VaultEntry> returnValues = new ArrayList<>();
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .limit(1l)
                .where()
                .eq(VaultEntry.ID_FIELD_NAME, id)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, "Error while db query", ex);
        return null;
    }
    return returnValues.get(0);
}
 
Example 6
Project: OpenDiabetes   File: VaultDao.java   Source Code and License 6 votes vote down vote up
public List<VaultEntry> queryVaultEntrysBetween(Date from, Date to) {
    List<VaultEntry> returnValues = new ArrayList<>();
    try {
        Date fromTimestamp = TimestampUtils.createCleanTimestamp(from);
        Date toTimestamp = TimestampUtils.createCleanTimestamp(to);

        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, fromTimestamp, toTimestamp)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, "Error while db query", ex);
    }
    return returnValues;
}
 
Example 7
Project: OpenDiabetes   File: VaultDao.java   Source Code and License 6 votes vote down vote up
public List<VaultEntry> queryBasalBetween(Date from, Date to) {
    List<VaultEntry> returnValues = null;
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.BASAL_MANUAL)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.BASAL_PROFILE)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.BASAL_INTERPRETER)
                .and()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, from, to)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, "Error while db query", ex);
    }
    return returnValues;
}
 
Example 8
Project: BachelorPraktikum   File: VaultDao.java   Source Code and License 6 votes vote down vote up
/**
 * This method is used to query {@link VaultEntry}s which are of a given type and lie in a specified period.
 * The types to be queried for are glucose types:
 * <ul>
 *     <li>{@link VaultEntryType#GLUCOSE_BG}</li>
 *     <li>{@link VaultEntryType#GLUCOSE_CGM}</li>
 *     <li>{@link VaultEntryType#GLUCOSE_CGM_ALERT}</li>
 * </ul>
 *
 * @param from The start of the period to query entries from.
 * @param to The end of the period to query entries from.
 * @return All {@link VaultEntry} which are of the required type and lie in the specified period.
 */
//TODO OTHER TYPES? Let's ask Jens @next meeting
public List<VaultEntry> queryGlucoseBetween(final Date from, final Date to) {
    List<VaultEntry> returnValues = null;
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_BG)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_CGM)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_CGM_ALERT)
                .and()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, from, to)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
    }
    return returnValues;
}
 
Example 9
Project: BachelorPraktikum   File: VaultDao.java   Source Code and License 6 votes vote down vote up
/**
 * This method is used to query {@link VaultEntry}s which are of a given type and lie in a specified period.
 * The types to be queried for are exercise types:
 * <ul>
 *     <li>{@link VaultEntryType#EXERCISE_BICYCLE}</li>
 *     <li>{@link VaultEntryType#EXERCISE_RUN}</li>
 *     <li>{@link VaultEntryType#EXERCISE_WALK}</li>
 *     <li>{@link VaultEntryType#EXERCISE_MANUAL}</li>
 * </ul>
 *
 * @param from The start of the period to query entries from.
 * @param to The end of the period to query entries from.
 * @return All {@link VaultEntry} which are of the required type and lie in the specified period.
 */
//TODO OTHER TYPES? Let's ask Jens @next meeting
public List<VaultEntry> queryExerciseBetween(final Date from, final Date to) {
    List<VaultEntry> returnValues = null;
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.EXERCISE_BICYCLE)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.EXERCISE_RUN)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.EXERCISE_WALK)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.EXERCISE_MANUAL)
                .and()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, from, to)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
    }
    return returnValues;
}
 
Example 10
Project: BachelorPraktikum   File: VaultDao.java   Source Code and License 6 votes vote down vote up
/**
 * This is used to retrieve an entry from the database by its identifier.
 *
 * @param id The ID of the {@link VaultEntry} to be retrieved.
 * @return The {@link VaultEntry} with respective ID or null.
 */
public VaultEntry queryVaultEntryById(final long id) {
    List<VaultEntry> returnValues;
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .limit(1L)
                .where()
                .eq(VaultEntry.ID_FIELD_NAME, id)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
        return null;
    }
    return returnValues.get(0);
}
 
Example 11
Project: BachelorPraktikum   File: VaultDao.java   Source Code and License 6 votes vote down vote up
/**
 * This is used to retrieve all {@link VaultEntry}s from the database which lie in the specified period of time, no matter their type.
 *
 * @param from The start of the time period to query entries from.
 * @param to The end of the time period to query entries from.
 * @return List of all {@link VaultEntry}s which lie in the specified time period.
 */
public List<VaultEntry> queryVaultEntriesBetween(final Date from, final Date to) {
    List<VaultEntry> returnValues = new ArrayList<>();
    try {
        Date fromTimestamp = TimestampUtils.createCleanTimestamp(from);
        Date toTimestamp = TimestampUtils.createCleanTimestamp(to);

        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, fromTimestamp, toTimestamp)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
    }
    return returnValues;
}
 
Example 12
Project: BachelorPraktikum   File: VaultDao.java   Source Code and License 6 votes vote down vote up
/**
 * This method is used to query {@link VaultEntry}s which are of a given type and lie in a specified period.
 * The types to be queried for are basal types:
 * <ul>
 *     <li>{@link VaultEntryType#BASAL_MANUAL}</li>
 *     <li>{@link VaultEntryType#BASAL_PROFILE}</li>
 *     <li>{@link VaultEntryType#BASAL_INTERPRETER}</li>
 * </ul>
 *
 * @param from The start of the period to query entries from.
 * @param to The end of the period to query entries from.
 * @return All {@link VaultEntry} which are of the required type and lie in the specified period.
 */
public List<VaultEntry> queryBasalBetween(final Date from, final Date to) {
    List<VaultEntry> returnValues = null;
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.BASAL_MANUAL)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.BASAL_PROFILE)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.BASAL_INTERPRETER)
                .and()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, from, to)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
    }
    return returnValues;
}
 
Example 13
Project: ebookmgr   File: LibraryManager.java   Source Code and License 6 votes vote down vote up
public Tag getTag(final String aTag) {
    try {
        QueryBuilder<Tag, Long> queryBuilder = dbHelper.getTagDao().queryBuilder();
        Where<Tag, Long> where = queryBuilder.where();
        SelectArg selectArg = new SelectArg();

        // define our query as 'name = ?'
        where.eq(Tag.COLUMN_NAME_TITLE, selectArg);

        // prepare it so it is ready for later query or iterator calls
        PreparedQuery<Tag> preparedQuery = queryBuilder.prepare();

        // later we can set the select argument and issue the query
        selectArg.setValue(aTag);
        List<Tag> tgs = dbHelper.getTagDao().query(preparedQuery);
        if (!tgs.isEmpty()) {
            return tgs.get(0);
        }
    } catch (java.sql.SQLException pE) {
        pE.printStackTrace();
    }
    return null;
}
 
Example 14
Project: ebookmgr   File: LibraryManager.java   Source Code and License 6 votes vote down vote up
public EBook getBook(final String fullFilename) {
    EBook ebk = null;
    try {
        QueryBuilder<EBook, Long> queryBuilder = dbHelper.getEBookDao().queryBuilder();
        Where<EBook, Long> where = queryBuilder.where();
        SelectArg selectArg = new SelectArg();

        // define our query as 'name = ?'
        where.eq(EBook.COLUMN_FULL_FILE_NAME, selectArg);

        // prepare it so it is ready for later query or iterator calls
        PreparedQuery<EBook> preparedQuery = queryBuilder.prepare();

        // later we can set the select argument and issue the query
        selectArg.setValue(fullFilename);
        List<EBook> result = dbHelper.getEBookDao().query(preparedQuery);

        if (result.size() > 0) {
            ebk = result.get(0);
        }
    } catch (java.sql.SQLException pE) {
        BookLibApplication.getInstance().e("Exception reading ebooks", pE);
    }
    return ebk;
}
 
Example 15
Project: ebookmgr   File: LibraryManager.java   Source Code and License 6 votes vote down vote up
public FileType getFileType(final String aFileType) {
    try {
        QueryBuilder<FileType, Long> queryBuilder = dbHelper.getFileTypeDao().queryBuilder();
        Where<FileType, Long> where = queryBuilder.where();
        SelectArg selectArg = new SelectArg();

        // define our query as 'name = ?'
        where.eq(FileType.COLUMN_NAME_TITLE, selectArg);

        // prepare it so it is ready for later query or iterator calls
        PreparedQuery<FileType> preparedQuery = queryBuilder.prepare();

        // later we can set the select argument and issue the query
        selectArg.setValue(aFileType);
        List<FileType> tgs = dbHelper.getFileTypeDao().query(preparedQuery);
        if (!tgs.isEmpty()) {
            return tgs.get(0);
        }
    } catch (java.sql.SQLException pE) {
        pE.printStackTrace();
    }
    return null;
}
 
Example 16
Project: ebookmgr   File: LibraryManager.java   Source Code and License 6 votes vote down vote up
public Author getAuthor(final String pFirstname, final String pLastname) {
    try {
        QueryBuilder<Author, Long> queryBuilder = dbHelper.getAuthorDao().queryBuilder();
        Where<Author, Long> where = queryBuilder.where();
        SelectArg selectArg = new SelectArg();

        // define our query as 'name = ?'
        where.eq(Author.COLUMN_NAME_FIRSTNAME, selectArg);

        // prepare it so it is ready for later query or iterator calls
        PreparedQuery<Author> preparedQuery = queryBuilder.prepare();

        // later we can set the select argument and issue the query
        selectArg.setValue(pFirstname);
        List<Author> tgs = dbHelper.getAuthorDao().query(preparedQuery);
        if (!tgs.isEmpty()) {
            return tgs.get(0);
        }
    } catch (java.sql.SQLException pE) {
        pE.printStackTrace();
    }
    return null;
}
 
Example 17
Project: ebookmgr   File: LibraryManager.java   Source Code and License 6 votes vote down vote up
public List<EBook> searchBooksMatching(final String searchStr) {
    List<EBook> result = new ArrayList<>();
    try {
        QueryBuilder<EBook, Long> queryBuilder = dbHelper.getEBookDao().queryBuilder();
        Where<EBook, Long> where = queryBuilder.where();
        SelectArg selectArg2 = new SelectArg();
        selectArg2.setValue("%" + searchStr + "%");
        SelectArg selectArg1 = new SelectArg();
        selectArg1.setValue("%" + searchStr + "%");

        // define our query as 'name = ?'
        where.like(EBook.COLUMN_FULL_FILE_NAME, selectArg1).or()
                .like(EBook.COLUMN_BOOK_TITLE, selectArg2);

        // prepare it so it is ready for later query or iterator calls
        PreparedQuery<EBook> preparedQuery = queryBuilder.prepare();

        // later we can set the select argument and issue the query
        result = dbHelper.getEBookDao().query(preparedQuery);
    } catch (SQLException pE) {
        pE.printStackTrace();
    }

    return result;
}
 
Example 18
Project: AndroidBase   File: OrmLiteDao.java   Source Code and License 6 votes vote down vote up
/**
 * 获取满足指定条件的记录数
 *
 * @param map 查询条件键值组合
 * @return
 */
public long getCount(Map<String, Object> map) {
    long count = 0;
    QueryBuilder queryBuilder = ormLiteDao.queryBuilder();
    queryBuilder.setCountOf(true);
    Where where = queryBuilder.where();
    try {
        where.isNotNull("id");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            where.and().eq(entry.getKey(), entry.getValue());
        }
        PreparedQuery<T> preparedQuery = queryBuilder.prepare();
        count = ormLiteDao.countOf(preparedQuery);
    } catch (SQLException e) {
        LogUtils.e(e);
    }
    return count;
}
 
Example 19
Project: AndroidAPS   File: FoodHelper.java   Source Code and License 6 votes vote down vote up
public Food findFoodById(String _id) {
    try {
        QueryBuilder<Food, Long> queryBuilder = getDaoFood().queryBuilder();
        Where where = queryBuilder.where();
        where.eq("_id", _id);
        PreparedQuery<Food> preparedQuery = queryBuilder.prepare();
        List<Food> list = getDaoFood().query(preparedQuery);

        if (list.size() == 1) {
            return list.get(0);
        } else {
            return null;
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return null;
}
 
Example 20
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
@Nullable
public static BgReading lastBg() {
    List<BgReading> bgList = null;

    try {
        Dao<BgReading, Long> daoBgReadings = MainApp.getDbHelper().getDaoBgReadings();
        QueryBuilder<BgReading, Long> queryBuilder = daoBgReadings.queryBuilder();
        queryBuilder.orderBy("date", false);
        queryBuilder.limit(1L);
        queryBuilder.where().gt("value", 38);
        PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
        bgList = daoBgReadings.query(preparedQuery);

    } catch (SQLException e) {
        log.debug(e.getMessage(), e);
    }
    if (bgList != null && bgList.size() > 0)
        return bgList.get(0);
    else
        return null;
}
 
Example 21
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public List<BgReading> getBgreadingsDataFromTime(long mills, boolean ascending) {
    try {
        Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
        List<BgReading> bgReadings;
        QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
        queryBuilder.orderBy("date", ascending);
        Where where = queryBuilder.where();
        where.ge("date", mills).and().gt("value", 38);
        PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
        bgReadings = daoBgreadings.query(preparedQuery);
        return bgReadings;
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return new ArrayList<BgReading>();
}
 
Example 22
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public int deleteDbRequestbyMongoId(String action, String id) {
    try {
        QueryBuilder<DbRequest, String> queryBuilder = getDaoDbRequest().queryBuilder();
        Where where = queryBuilder.where();
        where.eq("_id", id).and().eq("action", action);
        queryBuilder.limit(10L);
        PreparedQuery<DbRequest> preparedQuery = queryBuilder.prepare();
        List<DbRequest> dbList = getDaoDbRequest().query(preparedQuery);
        if (dbList.size() != 1) {
            log.error("deleteDbRequestbyMongoId query size: " + dbList.size());
        } else {
            //log.debug("Treatment findTreatmentById found: " + trList.get(0).log());
            return delete(dbList.get(0));
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return 0;
}
 
Example 23
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
@Nullable
public Treatment findTreatmentById(String _id) {
    try {
        Dao<Treatment, Long> daoTreatments = getDaoTreatments();
        QueryBuilder<Treatment, Long> queryBuilder = daoTreatments.queryBuilder();
        Where where = queryBuilder.where();
        where.eq("_id", _id);
        queryBuilder.limit(10L);
        PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
        List<Treatment> trList = daoTreatments.query(preparedQuery);
        if (trList.size() != 1) {
            //log.debug("Treatment findTreatmentById query size: " + trList.size());
            return null;
        } else {
            //log.debug("Treatment findTreatmentById found: " + trList.get(0).log());
            return trList.get(0);
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return null;
}
 
Example 24
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public List<Treatment> getTreatmentDataFromTime(long mills, boolean ascending) {
    try {
        Dao<Treatment, Long> daoTreatments = getDaoTreatments();
        List<Treatment> treatments;
        QueryBuilder<Treatment, Long> queryBuilder = daoTreatments.queryBuilder();
        queryBuilder.orderBy("date", ascending);
        Where where = queryBuilder.where();
        where.ge("date", mills);
        PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
        treatments = daoTreatments.query(preparedQuery);
        return treatments;
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return new ArrayList<Treatment>();
}
 
Example 25
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public List<TempTarget> getTemptargetsDataFromTime(long mills, boolean ascending) {
    try {
        Dao<TempTarget, Long> daoTempTargets = getDaoTempTargets();
        List<TempTarget> tempTargets;
        QueryBuilder<TempTarget, Long> queryBuilder = daoTempTargets.queryBuilder();
        queryBuilder.orderBy("date", ascending);
        Where where = queryBuilder.where();
        where.ge("date", mills);
        PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
        tempTargets = daoTempTargets.query(preparedQuery);
        return tempTargets;
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return new ArrayList<TempTarget>();
}
 
Example 26
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public TempTarget findTempTargetById(String _id) {
    try {
        QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
        Where where = queryBuilder.where();
        where.eq("_id", _id);
        PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
        List<TempTarget> list = getDaoTempTargets().query(preparedQuery);

        if (list.size() == 1) {
            return list.get(0);
        } else {
            return null;
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return null;
}
 
Example 27
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) {
    List<DanaRHistoryRecord> historyList;
    try {
        QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
        queryBuilder.orderBy("recordDate", false);
        Where where = queryBuilder.where();
        where.eq("recordCode", type);
        queryBuilder.limit(200L);
        PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
        historyList = getDaoDanaRHistory().query(preparedQuery);
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
        historyList = new ArrayList<>();
    }
    return historyList;
}
 
Example 28
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public void updateDanaRHistoryRecordId(JSONObject trJson) {
    try {
        QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
        Where where = queryBuilder.where();
        where.ge("bytes", trJson.get(DanaRNSHistorySync.DANARSIGNATURE));
        PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
        List<DanaRHistoryRecord> list = getDaoDanaRHistory().query(preparedQuery);
        if (list.size() == 0) {
            // Record does not exists. Ignore
        } else if (list.size() == 1) {
            DanaRHistoryRecord record = list.get(0);
            if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
                if (Config.logIncommingData)
                    log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
                record._id = trJson.getString("_id");
                getDaoDanaRHistory().update(record);
            } else {
                // already set
            }
        }
    } catch (SQLException | JSONException e) {
        log.error("Unhandled exception", e);
    }
}
 
Example 29
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public TemporaryBasal findTempBasalById(String _id) {
    try {
        QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
        queryBuilder = getDaoTemporaryBasal().queryBuilder();
        Where where = queryBuilder.where();
        where.eq("_id", _id);
        PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
        List<TemporaryBasal> list = getDaoTemporaryBasal().query(preparedQuery);

        if (list.size() != 1) {
            return null;
        } else {
            return list.get(0);
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return null;
}
 
Example 30
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public ExtendedBolus findExtendedBolusById(String _id) {
    try {
        QueryBuilder<ExtendedBolus, Long> queryBuilder = null;
        queryBuilder = getDaoExtendedBolus().queryBuilder();
        Where where = queryBuilder.where();
        where.eq("_id", _id);
        PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
        List<ExtendedBolus> list = getDaoExtendedBolus().query(preparedQuery);

        if (list.size() == 1) {
            return list.get(0);
        } else {
            return null;
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return null;
}
 
Example 31
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
@Nullable
public CareportalEvent getLastCareportalEvent(String event) {
    try {
        List<CareportalEvent> careportalEvents;
        QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
        queryBuilder.orderBy("date", false);
        Where where = queryBuilder.where();
        where.eq("eventType", event);
        queryBuilder.limit(1L);
        PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
        careportalEvents = getDaoCareportalEvents().query(preparedQuery);
        if (careportalEvents.size() == 1)
            return careportalEvents.get(0);
        else
            return null;
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return null;
}
 
Example 32
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public void deleteCareportalEventById(String _id) {
    try {
        QueryBuilder<CareportalEvent, Long> queryBuilder = null;
        queryBuilder = getDaoCareportalEvents().queryBuilder();
        Where where = queryBuilder.where();
        where.eq("_id", _id);
        PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
        List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);

        if (list.size() == 1) {
            CareportalEvent record = list.get(0);
            if (Config.logIncommingData)
                log.debug("Removing CareportalEvent record from database: " + record.log());
            delete(record);
        } else {
            if (Config.logIncommingData)
                log.debug("CareportalEvent not found database: " + _id);
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
}
 
Example 33
Project: AndroidAPS   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public ProfileSwitch findProfileSwitchById(String _id) {
    try {
        QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
        Where where = queryBuilder.where();
        where.eq("_id", _id);
        PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
        List<ProfileSwitch> list = getDaoProfileSwitch().query(preparedQuery);

        if (list.size() == 1) {
            return list.get(0);
        } else {
            return null;
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return null;
}
 
Example 34
Project: com-android   File: Utils.java   Source Code and License 6 votes vote down vote up
public static void bucketOps(String path, Boolean bucket, Context mContext) {
    final OrmHandler ormHandler = OpenHelperManager.getHelper(mContext, OrmHandler.class);
    try {
        Dao<Track, String> dbTrack = ormHandler.getDao(Track.class);
        QueryBuilder<Track, String> queryBuilder = dbTrack.queryBuilder();
        SelectArg selectArg = new SelectArg();
        queryBuilder.where().eq("path", selectArg);
        PreparedQuery<Track> preparedQuery = queryBuilder.prepare();
        selectArg.setValue(path);
        List<Track> lister = dbTrack.query(preparedQuery);
        Track temp_track = lister.get(0);
        temp_track.setBucket(bucket);
        dbTrack.update(temp_track);
        BUCKET_OPS = true;
    } catch (SQLException | IndexOutOfBoundsException e) {
        e.printStackTrace();
    }
}
 
Example 35
Project: Meducated-Ninja   File: NewsFragment.java   Source Code and License 6 votes vote down vote up
public PreparedQuery<Item> getPreparedQuery() {
    PreparedQuery<Item> preparedQuery = null;
    try {
        QueryBuilder<Item, Long> queryBuilder = getNewsItemDao().queryBuilder();
        queryBuilder.orderBy("pubDate",false);
        preparedQuery = queryBuilder.prepare();
    }
    catch (Exception e) {
        Timber.e(e,"prepared query generation failed.");
    }
    if (queryAdapter == null) {
        queryAdapter = new ORMQueryAdapter<>(getActivity().getApplicationContext(),R.layout.news_item, preparedQuery, new NewsListBinder());
        if (listView != null) {
            listView.setAdapter(queryAdapter);
        }
    }
    return preparedQuery;
}
 
Example 36
Project: mage-android   File: ObservationFeedFragment.java   Source Code and License 6 votes vote down vote up
private Cursor obtainCursor(PreparedQuery<Observation> query, Dao<Observation, Long> oDao) throws SQLException {
	Cursor c = null;
	CloseableIterator<Observation> iterator = oDao.iterator(query);

	// get the raw results which can be cast under Android
	AndroidDatabaseResults results = (AndroidDatabaseResults) iterator.getRawResults();
	c = results.getRawCursor();
	if (c.moveToLast()) {
		long oldestTime = c.getLong(c.getColumnIndex("last_modified"));
		Log.i(LOG_NAME, "last modified is: " + c.getLong(c.getColumnIndex("last_modified")));
		Log.i(LOG_NAME, "querying again in: " + (oldestTime - requeryTime)/60000 + " minutes");
		if (queryUpdateHandle != null) {
			queryUpdateHandle.cancel(true);
		}
		queryUpdateHandle = scheduler.schedule(new Runnable() {
			public void run() {
				updateFilter();
			}
		}, oldestTime - requeryTime, TimeUnit.MILLISECONDS);
		c.moveToFirst();
	}
	return c;
}
 
Example 37
Project: mage-android   File: PeopleFeedFragment.java   Source Code and License 6 votes vote down vote up
private Cursor obtainCursor(PreparedQuery<Location> query, Dao<Location, Long> lDao) throws SQLException {
    Cursor c = null;
    CloseableIterator<Location> iterator = lDao.iterator(query);

    // get the raw results which can be cast under Android
    AndroidDatabaseResults results = (AndroidDatabaseResults) iterator.getRawResults();
    c = results.getRawCursor();
    if (c.moveToLast()) {
        if (queryUpdateHandle != null) {
            queryUpdateHandle.cancel(true);
        }
        queryUpdateHandle = scheduler.schedule(new Runnable() {
            public void run() {
                updateTimeFilter(getTimeFilterId());
            }
        }, 30*1000, TimeUnit.MILLISECONDS);
        c.moveToFirst();
    }
    return c;
}
 
Example 38
Project: QuizUpWinner   File: BaseDaoImpl.java   Source Code and License 6 votes vote down vote up
public long countOf(PreparedQuery<T> paramPreparedQuery)
{
  checkForInitialized();
  if (paramPreparedQuery.getType() != StatementBuilder.StatementType.SELECT_LONG)
    throw new IllegalArgumentException("Prepared query is not of type " + StatementBuilder.StatementType.SELECT_LONG + ", did you call QueryBuilder.setCountOf(true)?");
  DatabaseConnection localDatabaseConnection = this.connectionSource.getReadOnlyConnection();
  try
  {
    long l = this.statementExecutor.queryForLong(localDatabaseConnection, paramPreparedQuery);
    return l;
  }
  finally
  {
    this.connectionSource.releaseConnection(localDatabaseConnection);
  }
}
 
Example 39
Project: chailmis-android   File: StockItemSnapshotService.java   Source Code and License 6 votes vote down vote up
public StockItemSnapshot getLatest(final Commodity commodity, final Date currentDate) {
    return dbUtil.withDao(StockItemSnapshot.class,
            new DbUtil.Operation<StockItemSnapshot, StockItemSnapshot>() {
                @Override
                public StockItemSnapshot operate(Dao<StockItemSnapshot, String> dao) throws SQLException {
                    QueryBuilder<StockItemSnapshot, String> queryBuilder = dao.queryBuilder();
                    queryBuilder.where().eq("commodity_id", commodity.getId()).and().eq("created", currentDate);
                    queryBuilder.orderBy("created", false);
                    PreparedQuery<StockItemSnapshot> query = queryBuilder.prepare();

                    return dao.queryForFirst(query);
                }
            }
    );

}
 
Example 40
Project: QuizUpWinner   File: BaseForeignCollection.java   Source Code and License 6 votes vote down vote up
protected PreparedQuery<T> getPreparedQuery()
{
  if (this.dao == null)
    return null;
  if (this.preparedQuery == null)
  {
    SelectArg localSelectArg = new SelectArg();
    localSelectArg.setValue(this.parentId);
    QueryBuilder localQueryBuilder = this.dao.queryBuilder();
    if (this.orderColumn != null)
      localQueryBuilder.orderBy(this.orderColumn, this.orderAscending);
    this.preparedQuery = localQueryBuilder.where().eq(this.foreignFieldType.getColumnName(), localSelectArg).prepare();
    if ((this.preparedQuery instanceof MappedPreparedStmt))
      ((MappedPreparedStmt)this.preparedQuery).setParentInformation(this.parent, this.parentId);
  }
  return this.preparedQuery;
}
 
Example 41
Project: chailmis-android   File: DispensingService.java   Source Code and License 6 votes vote down vote up
private int getDispensingsToPatientsThisMonth() {
    return dbUtil.withDao(Dispensing.class, new DbUtil.Operation<Dispensing, Integer>() {
        @Override
        public Integer operate(Dao<Dispensing, String> dao) throws SQLException {
            QueryBuilder<Dispensing, String> dispensingStringQueryBuilder = dao.queryBuilder();
            Date firstDay = Helpers.firstDayOfMonth(new Date());
            Date lastDay = Helpers.lastDayOfMonth(new Date());
            dispensingStringQueryBuilder.where().between("created", firstDay, lastDay);
            PreparedQuery<Dispensing> query = dispensingStringQueryBuilder.prepare();
            List<Dispensing> dispensingList = dao.query(query);
            return dispensingList.size();
        }


    });
}
 
Example 42
Project: q-municate-android   File: DialogOccupantDataManager.java   Source Code and License 6 votes vote down vote up
public List<DialogOccupant> getActualDialogOccupantsByIds(String dialogId, List<Integer> userIdsList) {
    List<DialogOccupant> dialogOccupantsList = Collections.emptyList();

    try {
        QueryBuilder<DialogOccupant, Long> queryBuilder = dao.queryBuilder();
        Where<DialogOccupant, Long> where = queryBuilder.where();
        where.and(
                where.in(QMUserColumns.ID, userIdsList),
                where.eq(DialogOccupant.Column.STATUS, DialogOccupant.Status.ACTUAL),
                where.eq(Dialog.Column.ID, dialogId)
        );
        PreparedQuery<DialogOccupant> preparedQuery = queryBuilder.prepare();
        dialogOccupantsList = dao.query(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return dialogOccupantsList;
}
 
Example 43
Project: q-municate-android   File: DialogOccupantDataManager.java   Source Code and License 6 votes vote down vote up
public List<DialogOccupant> getActualDialogOccupantsByDialog(String dialogId) {
    List<DialogOccupant> dialogOccupantsList = Collections.emptyList();

    try {
        QueryBuilder<DialogOccupant, Long> queryBuilder = dao.queryBuilder();
        Where<DialogOccupant, Long> where = queryBuilder.where();
        where.and(
                where.eq(DialogOccupant.Column.STATUS, DialogOccupant.Status.ACTUAL),
                where.eq(Dialog.Column.ID, dialogId)
        );
        PreparedQuery<DialogOccupant> preparedQuery = queryBuilder.prepare();
        dialogOccupantsList = dao.query(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return dialogOccupantsList;
}
 
Example 44
Project: q-municate-android   File: DialogNotificationDataManager.java   Source Code and License 6 votes vote down vote up
public List<DialogNotification> getDialogNotificationsByDialogId(String dialogId) {
    List<DialogNotification> dialogNotificationsList = new ArrayList<>();

    try {
        QueryBuilder<DialogNotification, Long> messageQueryBuilder = dao
                .queryBuilder();

        QueryBuilder<DialogOccupant, Long> dialogOccupantQueryBuilder = dialogOccupantDao
                .queryBuilder();

        QueryBuilder<Dialog, Long> dialogQueryBuilder = dialogDao.queryBuilder();
        dialogQueryBuilder.where().eq(Dialog.Column.ID, dialogId);

        dialogOccupantQueryBuilder.join(dialogQueryBuilder);
        messageQueryBuilder.join(dialogOccupantQueryBuilder);

        PreparedQuery<DialogNotification> preparedQuery = messageQueryBuilder.prepare();
        dialogNotificationsList = dao.query(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return dialogNotificationsList;
}
 
Example 45
Project: q-municate-android   File: DialogNotificationDataManager.java   Source Code and License 6 votes vote down vote up
public DialogNotification getLastDialogNotificationByDialogId(List<Long> dialogOccupantsList) {
    DialogNotification dialogNotification = null;

    try {
        QueryBuilder<DialogNotification, Long> queryBuilder = dao.queryBuilder();
        Where<DialogNotification, Long> where = queryBuilder.where();
        where.in(DialogOccupant.Column.ID, dialogOccupantsList);
        queryBuilder.orderBy(DialogNotification.Column.CREATED_DATE, false);
        PreparedQuery<DialogNotification> preparedQuery = queryBuilder.prepare();
        dialogNotification = dao.queryForFirst(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return dialogNotification;
}
 
Example 46
Project: q-municate-android   File: DialogNotificationDataManager.java   Source Code and License 6 votes vote down vote up
public DialogNotification getDialogNotificationByDialogId(boolean firstMessage, List<Long> dialogOccupantsList) {
    DialogNotification dialogNotification = null;

    try {
        QueryBuilder<DialogNotification, Long> queryBuilder = dao.queryBuilder();
        Where<DialogNotification, Long> where = queryBuilder.where();
        where.and(
                where.in(DialogOccupant.Column.ID, dialogOccupantsList),
                where.eq(DialogNotification.Column.STATE, State.READ)
        );
        queryBuilder.orderBy(DialogNotification.Column.CREATED_DATE, firstMessage);
        PreparedQuery<DialogNotification> preparedQuery = queryBuilder.prepare();
        dialogNotification = dao.queryForFirst(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return dialogNotification;
}
 
Example 47
Project: q-municate-android   File: FriendDataManager.java   Source Code and License 6 votes vote down vote up
public List<Friend> getAllSorted() {
    List<Friend> friendsList = Collections.emptyList();

    try {
        QueryBuilder<Friend, Long> friendQueryBuilder = dao.queryBuilder();

        QueryBuilder<QMUser, Long> userQueryBuilder = userDao.queryBuilder();
        userQueryBuilder.orderByRaw(QMUserColumns.FULL_NAME + " COLLATE NOCASE");

        friendQueryBuilder.join(userQueryBuilder);

        PreparedQuery<Friend> preparedQuery = friendQueryBuilder.prepare();

        friendsList = dao.query(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return friendsList;
}
 
Example 48
Project: q-municate-android   File: MessageDataManager.java   Source Code and License 6 votes vote down vote up
public Message getMessageByDialogId(boolean firstMessage, List<Long> dialogOccupantsList) {
    Message message = null;

    try {
        QueryBuilder<Message, Long> queryBuilder = dao.queryBuilder();
        Where<Message, Long> where = queryBuilder.where();
        where.and(
                where.in(DialogOccupant.Column.ID, dialogOccupantsList),
                where.eq(Message.Column.STATE, State.READ)
        );
        queryBuilder.orderBy(Message.Column.CREATED_DATE, firstMessage);
        PreparedQuery<Message> preparedQuery = queryBuilder.prepare();
        message = dao.queryForFirst(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return message;
}
 
Example 49
Project: q-municate-android   File: MessageDataManager.java   Source Code and License 6 votes vote down vote up
public Message getLastMessageByDialogId(List<Long> dialogOccupantsList) {
    Message message = null;

    try {
        QueryBuilder<Message, Long> queryBuilder = dao.queryBuilder();
        Where<Message, Long> where = queryBuilder.where();
        where.in(DialogOccupant.Column.ID, dialogOccupantsList);
        queryBuilder.orderBy(Message.Column.CREATED_DATE, false);
        PreparedQuery<Message> preparedQuery = queryBuilder.prepare();
        message = dao.queryForFirst(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return message;
}
 
Example 50
Project: q-municate-android   File: MessageDataManager.java   Source Code and License 6 votes vote down vote up
public List<Message> getMessagesByDialogId(String dialogId) {
    List<Message> messagesList = new ArrayList<>();

    try {
        QueryBuilder<Message, Long> messageQueryBuilder = dao.queryBuilder();

        QueryBuilder<DialogOccupant, Long> dialogOccupantQueryBuilder = dialogOccupantDao.queryBuilder();

        QueryBuilder<Dialog, Long> dialogQueryBuilder = dialogDao.queryBuilder();
        dialogQueryBuilder.where().eq(Dialog.Column.ID, dialogId);

        dialogOccupantQueryBuilder.join(dialogQueryBuilder);
        messageQueryBuilder.join(dialogOccupantQueryBuilder);

        PreparedQuery<Message> preparedQuery = messageQueryBuilder.prepare();
        messagesList = dao.query(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return messagesList;
}
 
Example 51
Project: q-municate-android   File: MessageDataManager.java   Source Code and License 6 votes vote down vote up
public List<Message> getMessagesByDialogIdLimeted(String dialogId, long limit) {
    List<Message> messagesList = new ArrayList<>();

    try {
        QueryBuilder<Message, Long> messageQueryBuilder = dao.queryBuilder();

        QueryBuilder<DialogOccupant, Long> dialogOccupantQueryBuilder = dialogOccupantDao.queryBuilder();

        QueryBuilder<Dialog, Long> dialogQueryBuilder = dialogDao.queryBuilder();
        dialogQueryBuilder.where().eq(Dialog.Column.ID, dialogId);

        dialogOccupantQueryBuilder.join(dialogQueryBuilder);
        messageQueryBuilder
                .join(dialogOccupantQueryBuilder)
                .orderBy(Message.Column.CREATED_DATE, false)
                .limit(limit);

        PreparedQuery<Message> preparedQuery = messageQueryBuilder.prepare();
        messagesList = dao.query(preparedQuery);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }

    return messagesList;
}
 
Example 52
Project: itmarry   File: MyRwTab.java   Source Code and License 6 votes vote down vote up
private void geneItems(int pageIndex, int size) {
	try {
		rwDao = dataHelper.getRwDao();
		QueryBuilder<Rw, Integer> qb = rwDao.queryBuilder();
		qb.offset(pageIndex * size);
		qb.limit(size);

		qb.where().eq("rwzt_dm", 6).and()
				.like("Gddw", "%" + gddw_key + "%")
				.and().like("yhmc", "%" + yh_mc_key + "%")
				.and().like("Dbzch", "%" + dbzch_key + "%")
				.and().like("zcbh", "%" + zcbh_key + "%")
				.and().like("azdz", "%" + azdz_key + "%");

		Log.d("sql:", qb.prepareStatementString());
		PreparedQuery<Rw> preparedQuery = qb.prepare();
		items.addAll(rwDao.query(preparedQuery));

	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example 53
Project: iSCAU-Android   File: ClassHelper.java   Source Code and License 6 votes vote down vote up
/**
 * help to build a where to query in database;;
 * @return
 */
private PreparedQuery buildWhere(String wantDay,int schoolWeek,String schoolWeekDsz) throws SQLException {
    QueryBuilder<ClassModel,Integer> queryBuilder = classDao.queryBuilder();
    queryBuilder.clear();
    Where<ClassModel,Integer> where = queryBuilder.where();
    where.and(
            where.like("day",wantDay),
            where.le("strWeek", schoolWeek),
            where.ge("endWeek", schoolWeek),
            where.or(
                    where.isNull("dsz"),
                    where.like("dsz",""),
                    where.like("dsz",schoolWeekDsz)
            )
    );
    return queryBuilder.prepare();
}
 
Example 54
Project: Man-Man   File: ManCacheFragment.java   Source Code and License 6 votes vote down vote up
@Override
public Loader<List<ManPage>> onCreateLoader(int i, Bundle args) {
    return new AbstractNetworkAsyncLoader<List<ManPage>>(getActivity()) {

        @Nullable
        @Override
        public List<ManPage> loadInBackground() {
            // check the DB for cached pages
            try {
                PreparedQuery<ManPage> query = DbProvider.getHelper().getManPagesDao().queryBuilder().where().like("name", "%" + mSearchCache.getQuery().toString() + "%").prepare();
                return DbProvider.getHelper().getManPagesDao().query(query);
            } catch (SQLException e) {
                Log.e(Utils.MM_TAG, "Exception while querying DB for cached page", e);
                Utils.showToastFromAnyThread(getActivity(), R.string.database_retrieve_error);
            }
            return null;
        }
    };
}
 
Example 55
Project: philippine-income-tax-android   File: PagibigModel.java   Source Code and License 6 votes vote down vote up
public Pagibig getPagibig(double salaryRate, int monthlyFrequency) {
	salaryRate = salaryRate * monthlyFrequency;
	QueryBuilder<Pagibig, Integer> qb = pagibigDao.queryBuilder();
	try {
		PreparedQuery<Pagibig> preparedQuery = qb.where()
				.le("salaryRateFrom", salaryRate).and()
				.ge("salaryRateTo", salaryRate).prepare();
		Pagibig pagibig = pagibigDao.queryForFirst(preparedQuery);
		pagibig.setSalaryRate(salaryRate, monthlyFrequency);
		return pagibig;
	} catch (SQLException e) {
		e.printStackTrace();
	}

	return null;
}
 
Example 56
Project: philippine-income-tax-android   File: WithholdingTaxModel.java   Source Code and License 6 votes vote down vote up
private WithholdingTax computeWithholdingTax(double taxableIncome,
		int dependents, int withholdingTaxTypeId,
		String computationFrequency) {
	QueryBuilder<WithholdingTax, Integer> qb = withholdingTaxDao
			.queryBuilder();
	try {
		PreparedQuery<WithholdingTax> pq = qb.where()
				.eq("withholdingTaxTypeId", withholdingTaxTypeId).and()
				.eq("dependents", dependents).and()
				.eq("computationFrequency", computationFrequency).and()
				.le("taxableIncomeFrom", taxableIncome).and()
				.ge("taxableIncomeTo", taxableIncome).prepare();
		// Log.i("wt", pq.getStatement());
		WithholdingTax withholdingTax = withholdingTaxDao.queryForFirst(pq);
		withholdingTax.setTaxableIncome(taxableIncome);
		return withholdingTax;
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 57
Project: chailmis-android   File: StockItemSnapshotService.java   Source Code and License 6 votes vote down vote up
public StockItemSnapshot get(final Commodity commodity, final Date date) throws Exception {
    List<StockItemSnapshot> stockItemSnapshots = dbUtil.withDao(StockItemSnapshot.class,
            new DbUtil.Operation<StockItemSnapshot, List<StockItemSnapshot>>() {
                @Override
                public List<StockItemSnapshot> operate(Dao<StockItemSnapshot, String> dao) throws SQLException {
                    QueryBuilder<StockItemSnapshot, String> queryBuilder = dao.queryBuilder();
                    queryBuilder.where().eq("commodity_id", commodity.getId()).and().eq("created", date);
                    PreparedQuery<StockItemSnapshot> query = queryBuilder.prepare();

                    return dao.query(query);
                }
            }
    );

    if (stockItemSnapshots.size() > 1) {
        throw new Exception("Multiple stock item snapshots found for " + commodity.getName() +
                " on " + new SimpleDateFormat("yyyy-MM-dd").format(date));
    }

    if (stockItemSnapshots.size() == 1) {
        return stockItemSnapshots.get(0);
    }

    return null;
}
 
Example 58
Project: Diandi1.20   File: BaseDaoT.java   Source Code and License 6 votes vote down vote up
public List<T> query(Map<String, Object> map) throws SQLException {
    QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();
    if (!map.isEmpty()) {
        Where<T, Integer> wheres = queryBuilder.where();
        Set<String> keys = map.keySet();
        ArrayList<String> keyss = new ArrayList<String>();
        keyss.addAll(keys);
        for (int i = 0; i < keyss.size(); i++) {
            if (i == 0) {
                wheres.eq(keyss.get(i), map.get(keyss.get(i)));
            } else {
                wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));
            }
        }
    }
    PreparedQuery<T> preparedQuery = queryBuilder.prepare();
    return query(preparedQuery);
}
 
Example 59
Project: fwm   File: OMRegionInteractionDaoImpl.java   Source Code and License 5 votes vote down vote up
public List<OMRegionInteraction> queryForLike(String arg0, Object arg1) throws SQLException {
	PreparedQuery<OMRegionInteraction> preparedQuery;
	if (arg1 instanceof Integer){
		preparedQuery = this.queryBuilder().where().like(arg0, arg1).prepare();
	} else {
		preparedQuery = this.queryBuilder().where().like(arg0, "%" + arg1 + "%").prepare();
	}
	return this.query(preparedQuery);
}
 
Example 60
Project: fwm   File: RegionDaoImpl.java   Source Code and License 5 votes vote down vote up
public List<Region> queryForLike(String arg0, Object arg1) throws SQLException {
	PreparedQuery<Region> preparedQuery;
	if (arg1 instanceof Integer) {
		preparedQuery = this.queryBuilder().where().like(arg0, arg1).prepare();
	} else if (arg0.equals("name")) {
		preparedQuery = this.queryBuilder().where().like("ignoreCaseName", new SelectArg("%" + arg1 + "%")).prepare();
	} else {
		preparedQuery = this.queryBuilder().where().like(arg0, new SelectArg("%" + arg1 + "%")).prepare();
	}
	return this.query(preparedQuery);
}