I've tried to find the best pattern for sqlite in my android applications, but I just find general: "How to fetch data" etc... eg.: http://ift.tt/1oalrZT
But how should I organize the files? Where should I place the queries?
I use a contract file:
public final class DatabaseContract {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "feed.db";
private static final String TEXT_TYPE = " TEXT";
private static final String INT_TYPE = " INT";
private static final String LONG_TYPE = " LONG";
private static final String COMMA_SEP = ", ";
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
private DatabaseContract() {}
public static abstract class table_feedings implements BaseColumns {
public static final String TABLE_NAME = "feedings";
public static final String FEED_START = "feed_start";
public static final String FEED_END = "feed_end";
public static final String CODE = "code";
public static final String NOTE = "note";
public static final String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME + " (" +
_ID + " INTEGER PRIMARY KEY, " +
FEED_START + LONG_TYPE + COMMA_SEP +
FEED_END + LONG_TYPE + COMMA_SEP +
CODE + INT_TYPE + COMMA_SEP +
NOTE + TEXT_TYPE + " )";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
}
}
and a dbHelper:
public class FeedDbHelper extends SQLiteOpenHelper {
public FeedDbHelper(Context context) {
super(context, DatabaseContract.DATABASE_NAME, null, DatabaseContract.DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(DatabaseContract.table_feedings.CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(DatabaseContract.table_feedings.DELETE_TABLE);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
But where should the queries be placed? In a "query class"? or in one of the helping classes already defined?
`ContentValues values = new ContentValues();
values.put(DatabaseContract.table_feedings.FEED_START, feed_start);
values.put(DatabaseContract.table_feedings.FEED_END, feed_end);
values.put(DatabaseContract.table_feedings.CODE, code);
values.put(DatabaseContract.table_feedings.NOTE, "");
long newRowId;
newRowId = db.insert(
DatabaseContract.table_feedings.TABLE_NAME,
null,
values);
if(newRowId > 0)
Log.i("Hei", "Row added to db");
else
Log.e("Hei", "Error when writing to DB");`
Aucun commentaire:
Enregistrer un commentaire