简体   繁体   中英

How to insert the latest row_id of a table into a different table using Android and SQLite

I understand the title may sound confusing, but the goal is very clear:

I am building an application that requires two tables: tracks and waypoints.

A user enters the track name via a textfield and the table generates an ID under track_id.

in the waypoints table there is a column called track_id_fk. When the OnLocationChanged() method is called, the longitude and latitude is entered into the table, along with the time.

I want to add the track_id of the newest track entry in the track table to the track_id_fk column in the waypoints table.

I am using the following code:

SQLiteDatabase db = waypoints.getWritableDatabase();
        ContentValues waypointvalues = new ContentValues();
        waypointvalues.put(LONGITUDE, loc.getLongitude());
        waypointvalues.put(LATITUDE, loc.getLatitude());
        waypointvalues.put(TIME, System.currentTimeMillis());
        waypointvalues.put(TRACK_ID_FK, "last inserted trackid");
        db.insertOrThrow(TABLE_NAME, null, waypointvalues);

I am unsure as to what the value should be where "last inserted trackid" is.

Thanks

insertOrThrow Returns the row ID of the newly inserted row, or -1 if an error occurred

    SQLiteDatabase db1 = tracks.getWritableDatabase();
    ContentValues tracksvalues = new ContentValues();
    tracksvalues.put(COL1, '1');
    tracksvalues.put(COL2, '2');
    Long insertid=db1.insertOrThrow(TABLE_NAME1, null, tracksvalues);

    if (insertid!=-1) {

        SQLiteDatabase db2 = waypoints.getWritableDatabase();
        ContentValues waypointvalues = new ContentValues();
        waypointvalues.put(LONGITUDE, loc.getLongitude());
        waypointvalues.put(LATITUDE, loc.getLatitude());
        waypointvalues.put(TIME, System.currentTimeMillis());
        waypointvalues.put(TRACK_ID_FK, insertid);
        db2.insertOrThrow(TABLE_NAME2, null, waypointvalues);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM