mcclosa
mcclosa

Reputation: 1455

SQLite insert id from previous insert to populate value of column in another table

I am a newcomer to android programming and SQLite and have come across a hurdle. I have 3 tables in question; teams, leagues and a lookup table called teams_vs_leagues which holds the id of a team and the id of a league so they are linked. Below are the tables designs:

//Create teams Table
private static final String CREATE_TEAMS_TABLE = "CREATE TABLE "
        + TEAMS_TABLE + "("
        + ID + " INTEGER PRIMARY KEY,"
        + TEAM_NAME + " TEXT,"
        + IMAGE + " TEXT" + ")";

//Create leagues Table
private static final String CREATE_LEAGUES_TABLE = "CREATE TABLE "
        + LEAGUES_TABLE + "("
        + ID + " INTEGER PRIMARY KEY,"
        + LEAGUE_NAME + " TEXT" + ")";

//Create teams_vs_leagues Table
private static final String CREATE_TEAMS_VS_LEAGUES_TABLE = "CREATE TABLE "
        + TEAMS_VS_LEAGUES_TABLE + "("
        + ID + " INTEGER PRIMARY KEY,"
        + TEAM_ID + " INTEGER,"
        + LEAGUE_ID + " INTEGER,"
        + POINTS + " INTEGER"+ ")";

Below is currently the method I have of adding a new team:

public boolean createTeam(String team_name, String image, String team_id, String league_id, String points) {
 SQLiteDatabase db = this.getWritableDatabase();

 ContentValues values = new ContentValues();

 values.put(TEAM_NAME, team_name);
 values.put(IMAGE, image);

 long result = db.insert(TEAMS_TABLE, null, values);

 if (result == -1)
  return false;
 else
  return true;
}

How can I add TEAM_ID into the teams_vs_league table as the id from the insert above? Any help would be great appreciated.

Upvotes: 0

Views: 271

Answers (2)

sihao
sihao

Reputation: 431

According to the SQLite API Android SQLite API, the insert method returns the row ID of the newly inserted row, or -1 if an error occurred.

Therefore, you can make changes to your code as follow:

  long result = db.insert(TEAMS_TABLE, null, values);

  if (result == -1) { 
      //throw error here
      return false;
   } else { 
     //result contains the id needed
     //do something
     return true;
  }

Cheers! Happy Programming!

Upvotes: 1

Vasily Kabunov
Vasily Kabunov

Reputation: 6761

insert() method returns the row ID of the newly inserted row, or -1 if an error occurred.

So you can modify your code:

if (result == -1)
    return false;
else
    //create the record in the teams_vs_leagues here
    //using result as TEAM_ID and league_id as LEAGUE_ID 

    return true;
}

Upvotes: 0

Related Questions