Reputation: 3541
I have a DatabaseHelper
class that builds all my tables and handles queries, etc.
However, one thing stumps me.
I have a checklist
table with the following columns:
checklist_id, int, primary key
start_time, text
end_time, text
This is my "insertChecklist()" method, that inserts a row into the table:
public long insertChecklist(Checklist checklist){
// Get reference of the ChecklistDB database
SQLiteDatabase db = this.getWritableDatabase();
// Make values to be inserted
ContentValues values = new ContentValues();
values.put(ChecklistContract._ID, checklist.getId());
values.put(ChecklistContract.COLUMN_NAME_START_TIME, checklist.getStartTime());
values.put(ChecklistContract.COLUMN_NAME_END_TIME, checklist.getEndTime());
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
ChecklistContract.TABLE_NAME,
null, //COLUMN_NAME_NULLABLE (set to null to not insert new row where there are no values)
values);
// close database transaction
db.close();
return newRowId;
}
So I utilize this function as follows:
Checklist
objectinsertChecklist()
methodHowever, how do I know what to make the id in my Checklist object?
Checklist checklist = new Checklist(id??, startTime, endTime);
// the "id" needs to be the equal to the last id in the table, plus 1
insertChecklist(checklist);
Does anyone have experience with SQLite databases that could help me with this? Am I approaching this wrong?
Upvotes: 0
Views: 46
Reputation: 180020
The insert()
function returns the rowid
of the new row.
If your table has an autoincrementing ID, i.e., an INTEGER PRIMARY KEY or INTEGER PRIMARY KEY AUTOINCREMENT column, then this is the same as the rowid
.
In that case, to automatically assign a new value, do not put any ID value into the ContentValues
, and set the ID of your object to the value returned by insert()
:
public void insertChecklist(Checklist checklist) {
SQLiteDatabase db = this.getWritableDatabase();
try {
ContentValues values = new ContentValues();
values.put(ChecklistContract.COLUMN_NAME_START_TIME, checklist.getStartTime());
values.put(ChecklistContract.COLUMN_NAME_END_TIME, checklist.getEndTime());
long id;
id = db.insertOrThrow(ChecklistContract.TABLE_NAME, null, values);
checklist.setId(id);
} finally {
db.close();
}
}
Upvotes: 1