I have two tables in which the second table has a foreign key which is defined as table 1’s primary key. Under the add operation how can I reference the newly added table 1 key to use as table 2’s foreign key?
// Project Table columns names
private static final String KEY_ID = "id"; // Primary, integer
private static final String KEY_NAME = "name"; // Unique, text
// Images Table column names
private static final String KEY_IM_ID = "id"; // Primary, integer
private static final String IM_URI = "uri"; // text
private static final String PROJ_IMAGE_ID = "proImgId"; // foreign for Projects Table
public void addProject(Project project) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values_PT = new ContentValues(); // PROJECTS TABLE
ContentValues values_IT = new ContentValues(); // IMAGES TABLE
values_PT.put(KEY_NAME, project.getName()); // project name
// does the KEY ID get added on its own?
values_IT.put(IM_URI, project.getURI()); // image uri
values_IT.put(PROJ_IMAGE_ID, ????????);
}
PROJ_IMAGE_ID needs to have KEY_ID’s value, however I do not know how retrieve it. Is there a way to do this?
If your ID columns are declared as
INTEGER PRIMARY KEY, then they are autoincrementing and will get their value automatically if you don’t set them when inserting.To get the ID of a new record, you have to actually insert the record first; the new ID is the return value of the
insert()function.