- Create SQLite database.
Define a class derived from
SQLiteOpenHelper:
public class SDBH extends SQLiteOpenHelper {
public KidsDbHelper(Context context) {
super(context, "kids2.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// This method is only called if the database
// Does not exist.
// Recommendation: leave the body of this
// method empty. Put code for creating and
// populating tables in the activity file.
}
@Override
public void onUpgrade(SQLiteDatabase db,
int i, int i1) {
// We will not use this onUpgrade method
// in IT 372, but it is still required.
}
}
- Create SQLite table in the activity file:
SQLiteOpenHelper dbh = new KidsDbHelper(this);
SQLiteDatabase db = dbh.getReadableDatabase( );
db.execSQL("create table kids(name text,
gender text, age integer)");
- Insert row into table:
ContentValues studentValues = new ContentValues( );
studentValues.put("name", name);
studentValues.put("grade", grade);
studentValues.put("gender", gender);
db.insert("students", null, studentValues);
- Create Cursor to view or use query results:
Cursor cursor = db.query("students",
new String[ ] {"name", "grade", "gender"},
null, null, null, null, null);
The five null arguments correspond to these parameters:
selection selectionArgs groupBy having orderBy
We will see how to use these arguments later.
- Methods to position cursor within result set:
cursor.moveToFirst( )
cursor.moveToNext( )
cursor.moveToPrevious( )
cursor.moveToLast( )
- Methods to obtain field values from current cursor position:
cursor.getDouble(columnIndex)
cursor.getInt(columnIndex)
cursor.getString(columnIndex)