views:

72

answers:

1

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

+3  A: 

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);

    }
Pentium10
Thanks for the reply, this is exactly what I need, however, the values.put statements are in seperate methods.Inserting into the track table happens in the OnCreate() method, and inserting GPs coordinates into the waypoints table happens in the OnLocationChanged() method. How would I reference the insertid Long variable?
LordSnoutimus
Save it somewhere for later use. That's OOP question, if you still can't figure out, post a new question.
Pentium10
I just re-read my question, I think I was just having one of those days!, Obviously it just needed a Long trackid variable declaration at the top :) thanks for your help Pentium10!
LordSnoutimus