Permalink
Browse files

Evolução do AlienDroid.

  • Loading branch information...
1 parent db71b6b commit fe080c40c8deecac7c646952b95d7481ce0a3246 @hjort hjort committed Mar 26, 2012
@@ -4,6 +4,8 @@
import roboguice.application.RoboApplication;
+//TODO: criar respectivo módulo para usar em um RoboApplication
+// vide http://code.google.com/p/google-guice/wiki/GettingStarted
public class AlienApplication extends RoboApplication {
@Override
@@ -34,14 +34,18 @@
import com.google.inject.Singleton;
/**
- * Classe auxiliar que ajuda a abrir e manter uma conex‹o com o banco de dados.
+ * Classe auxiliar que ajuda a abrir e manter uma conexão com o banco de dados.
*
* @author Marlon Silva Carvalho
* @since 1.0.0
*/
@Singleton
public class DBOpenHelper extends SQLiteOpenHelper {
+
+ //TODO: especificar nome do banco de dados em arquivo de propriedades da aplicação
private static final String DATABASE_NAME = "database.db";
+
+ //TODO: especificar versão do banco de dados em arquivo de propriedades da aplicação
private static final int VERSION = 1;
@Inject
@@ -28,14 +28,15 @@
import android.database.Cursor;
/**
- * Seguindo padr�o de projeto ActiveRecord, toda classe que um 'Model' deve
- * herdar desta classe. J� ter� por padr�o os m�todos triviais para persistir o
+ * Seguindo padrão de projeto ActiveRecord, toda classe que é um 'Model' deve
+ * herdar desta classe. Já terá por padrão os métodos triviais para persistir o
* objeto, como insert() e update().
*
* @author Marlon Silva Carvalho
* @since 1.0.0
*/
abstract public class Model {
+
public Integer _id;
public Model(final Integer id) {
@@ -47,20 +48,20 @@ public Model() {
}
public void load(final Integer id) {
- String tableName = Reflection.getSimpleClassName(this);
- DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
- Cursor cursor = helper.getReadableDatabase().query(tableName,
- Reflection.getNonStaticDeclaredFieldsNames(this.getClass()), "_id=?", new String[] { id.toString() },
- null, null, null);
-
+ final String tableName = Reflection.getSimpleClassName(this);
+ final DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
+ final Cursor cursor = helper.getReadableDatabase().query(tableName,
+ Reflection.getNonStaticDeclaredFieldsNames(this.getClass()),
+ "_id=?", new String[] { id.toString() }, null, null, null);
if (cursor.moveToFirst()) {
transform(cursor);
}
cursor.close();
}
- public static <T extends Model> Model findFirst(final Class<T> cls, final String query, final String... params) {
- List<T> list = Model.where(cls, query, params);
+ public static <T extends Model> Model findFirst(final Class<T> cls,
+ final String query, final String... params) {
+ final List<T> list = Model.where(cls, query, params);
Model model = null;
if (list.size() > 0) {
model = list.iterator().next();
@@ -69,31 +70,31 @@ public void load(final Integer id) {
}
public static <T extends Model> Model findFirst(final Class<T> cls) {
- List<T> list = Model.where(cls, "1=1");
+ final List<T> list = Model.where(cls, "1=1");
Model model = null;
if (list.size() > 0) {
model = list.iterator().next();
}
return model;
}
-
/**
* Save the model to the database.
*/
public void save() {
- ColumnMapper mapper = Beans.getBean(ColumnMapper.class);
- ContentValues values = new ContentValues();
+ final ColumnMapper mapper = Beans.getBean(ColumnMapper.class);
+ final ContentValues values = new ContentValues();
- Field[] fields = Reflection.getNonStaticDeclaredFields(getClass());
+ final Field[] fields = Reflection.getNonStaticDeclaredFields(getClass());
for (Field field : fields) {
values.put(field.getName(), mapper.getValueFromObject(field, this));
}
- String tableName = Reflection.getSimpleClassName(this);
- DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
+ final String tableName = Reflection.getSimpleClassName(this);
+ final DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
if (_id != null) {
- helper.getWritableDatabase().update(tableName, values, "_id=?", new String[] { _id.toString() });
+ helper.getWritableDatabase().update(tableName, values, "_id=?",
+ new String[] { _id.toString() });
} else {
helper.getWritableDatabase().insertOrThrow(tableName, null, values);
}
@@ -103,14 +104,15 @@ public void save() {
* Delete the model from database.
*/
public void delete() {
- String tableName = Reflection.getSimpleClassName(this);
- DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
- helper.getWritableDatabase().delete(tableName, "_id=?", new String[] { _id.toString() });
+ final String tableName = Reflection.getSimpleClassName(this);
+ final DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
+ helper.getWritableDatabase().delete(tableName, "_id=?",
+ new String[] { _id.toString() });
}
protected void transform(final Cursor cursor) {
- ColumnMapper mapper = Beans.getBean(ColumnMapper.class);
- Field[] fields = Reflection.getNonStaticDeclaredFields(this.getClass());
+ final ColumnMapper mapper = Beans.getBean(ColumnMapper.class);
+ final Field[] fields = Reflection.getNonStaticDeclaredFields(this.getClass());
for (Field field : fields) {
mapper.setValueToObject(cursor, field, this);
}
@@ -121,12 +123,15 @@ protected void transform(final Cursor cursor) {
return where(cls, "1=1");
}
- public static <T extends Model> List<T> where(final Class<T> cls, final String query, final String... params) {
- String tableName = Reflection.getSimpleClassName(cls);
- List<T> result = new ArrayList<T>();
+ public static <T extends Model> List<T> where(final Class<T> cls,
+ final String query, final String... params) {
+
+ final String tableName = Reflection.getSimpleClassName(cls);
+ final List<T> result = new ArrayList<T>();
- DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
- Cursor cursor = helper.getReadableDatabase().rawQuery("select * from " + tableName + " where " + query, params);
+ final DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
+ final Cursor cursor = helper.getReadableDatabase().rawQuery(
+ "select * from " + tableName + " where " + query, params);
while (cursor.moveToNext()) {
T model = Reflection.instantiate(cls);
model.transform(cursor);
@@ -137,41 +142,78 @@ protected void transform(final Cursor cursor) {
return result;
}
+ public static <T extends Model> int count(final Class<T> cls) {
+ return count(cls, null);
+ }
+
+ public static <T extends Model> int count(final Class<T> cls,
+ final String query, final String... params) {
+
+ final String tableName = Reflection.getSimpleClassName(cls);
+ int result = 0;
+
+ StringBuffer sb = new StringBuffer();
+ sb.append("select count(1) from ");
+ sb.append(tableName);
+ if (query != null) {
+ sb.append(" where ");
+ sb.append(query);
+ }
+
+ final DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
+ final Cursor cursor = helper.getReadableDatabase().rawQuery(sb.toString(), params);
+ if (cursor.moveToNext()) {
+ result = cursor.getInt(0);
+ }
+
+ cursor.close();
+ return result;
+ }
+
public static String getSQLCreateTable(final Class<?> cls) {
- String tableName = Reflection.getSimpleClassName(cls);
- StringBuilder sql = new StringBuilder();
+ final String tableName = Reflection.getSimpleClassName(cls);
+ final StringBuilder sql = new StringBuilder();
+
sql.append("CREATE TABLE ");
sql.append(tableName);
sql.append(" (");
- sql.append(" _id INTEGER PRIMARY KEY, ");
- Field[] fields = Reflection.getNonStaticDeclaredFields(cls);
+ sql.append(" _id INTEGER PRIMARY KEY");
+
+ boolean first = true;
+ final Field[] fields = Reflection.getNonStaticDeclaredFields(cls);
+
for (Field field : fields) {
+ if (first) {
+ sql.append(", ");
+ first = false;
+ }
sql.append(field.getName());
sql.append(" ");
sql.append(getType(field));
- sql.append(", ");
}
- sql.delete(sql.length() - 2, sql.length());
sql.append(");");
+
return sql.toString();
}
private static String getType(final Field field) {
+ final Class<?> cls = field.getType();
+
String type = null;
- Class<?> cls = field.getType();
- if (cls.getSimpleName().toLowerCase().equals("date")) {
- type = "DATE";
- }
- if (cls.getSimpleName().toLowerCase().equals("string")) {
- type = "TEXT";
- }
- if (cls.getSimpleName().toLowerCase().equals("integer") || cls.getSimpleName().toLowerCase().equals("boolean")) {
+ if (cls.getSimpleName().toLowerCase().equals("integer")
+ || cls.getSimpleName().toLowerCase().equals("long")
+ || cls.getSimpleName().toLowerCase().equals("short")
+ || cls.getSimpleName().toLowerCase().equals("boolean")) {
type = "INTEGER";
- }
- if (cls.getSimpleName().toLowerCase().equals("double") || cls.getSimpleName().toLowerCase().equals("float")) {
+ } else if (cls.getSimpleName().toLowerCase().equals("double")
+ || cls.getSimpleName().toLowerCase().equals("float")) {
type = "REAL";
+ } else if (cls.getSimpleName().toLowerCase().equals("date")) {
+ type = "DATE";
+ } else {
+ type = "TEXT";
}
-
+
return type;
}

0 comments on commit fe080c4

Please sign in to comment.