mardi 2 février 2016

How to insert my first and subsequent rows into a my database for android project

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:

  1. I create a Checklist object
  2. I pass it into my insertChecklist() method

However, 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?

Aucun commentaire:

Enregistrer un commentaire