I’m creating an android application in which i will need to store data using SQLite. it needs to store date, days between 2 dates and some text fields. I have looked up some tutorials online and the method that i am most comfortable with is this one here:
public class DataHelper {
private static final String DATABASE_NAME = "example.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "table1";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
sorry about the long peice of code. I’m unsure if this way of using the database is even correct
DataHelper. Having aDataHelperto create your database and tables is a good plan. However, have yourDataHelperextend the SQLiteOpenHelper class so it is truly aHelperclass.DataHelperjust call theonCreatemethods for those tables/classes.ContentProviderthat helps you provide access to your data. Try providing access to your database strictly through your ownContentProvider. This provides better flexibility and a few levels of abstraction.Here are some examples that i have recently been working with. These are from another source as well, but modified a little. I am not sure where i got the original stuff. But here is what i have from what i was working on.
Hope this helps!