/** * Return the instance of an entity with a matching id. * * @param <T> Any ActiveRecordBase class. * @param type The class of the entity to return. * @param id The desired ID. * @return The matching entity if reocrd found in DB, null otherwise * @throws ActiveRecordException */ public <T extends ActiveRecordBase> T findByID(Class<T> type, long id) throws ActiveRecordException { if (m_Database == null) throw new ActiveRecordException("Set database first"); T entity = s_EntitiesMap.get(type, id); if (entity != null) return entity; try { entity = type.newInstance(); } catch (IllegalAccessException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } catch (InstantiationException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } Cursor c = m_Database.query(entity.getTableName(), null, "_id = ?", new String[] {String.valueOf(id)}); try { if (!c.moveToNext()) { return null; } else { entity.inflate(c); entity.m_NeedsInsert = false; entity.m_Database = m_Database; } } finally { c.close(); } return entity; }
/** * Return all instances of an entity that match the given criteria. Use whereClause to specify * condition, using reqular SQL syntax for WHERE clause. * * <p>For example selecting all JOHNs born in 2001 from USERS table may look like: * * <pre> * users.find(Users.class, "NAME='?' and YEAR=?", new String[] {"John", "2001"}); * </pre> * * @param <T> Any ActiveRecordBase class. * @param type The class of the entities to return. * @param whereClause The condition to match (Don't include "where"). * @param whereArgs The arguments to replace "?" with. * @return A generic list of all matching entities. * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstantiationException */ public <T extends ActiveRecordBase> List<T> find( Class<T> type, String whereClause, String[] whereArgs) throws ActiveRecordException { if (m_Database == null) throw new ActiveRecordException("Set database first"); T entity = null; try { entity = type.newInstance(); } catch (IllegalAccessException e1) { throw new ActiveRecordException(e1.getLocalizedMessage()); } catch (InstantiationException e1) { throw new ActiveRecordException(e1.getLocalizedMessage()); } List<T> toRet = new ArrayList<T>(); Cursor c = m_Database.query(entity.getTableName(), null, whereClause, whereArgs); try { while (c.moveToNext()) { entity = s_EntitiesMap.get(type, c.getLong(c.getColumnIndex("_id"))); if (entity == null) { entity = type.newInstance(); entity.m_Database = m_Database; entity.m_NeedsInsert = false; entity.inflate(c); } toRet.add(entity); } } catch (IllegalAccessException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } catch (InstantiationException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } finally { c.close(); } return toRet; }