public void update(Routine updatedRoutine) throws Exception {
    SQLiteDatabase database = dbHelper.getWritableDatabase();

    database.beginTransaction();
    try {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK);
      Date date = new Date();
      ContentValues values = new ContentValues();
      int routineId = updatedRoutine.getId();
      String[] whereArgs = new String[] {Integer.toString(routineId)};
      values.put(DbHelper.ROUTINE_NAME, updatedRoutine.getName());
      values.put(DbHelper.ROUTINE_DATE_UPDATED, dateFormat.format(date));

      database.update(DbHelper.ROUTINES, values, DbHelper.ROUTINE_ID + "=?", whereArgs);
      values.clear();
      database.delete(DbHelper.STEPS, DbHelper.STEP_ROUTINE_ID + "=?", whereArgs);
      saveSteps(updatedRoutine, database);
      database.setTransactionSuccessful();
    } catch (Exception e) {
      database.endTransaction();
      database.close();
      throw e;
    }
    database.endTransaction();
    database.close();
  }
 private void saveSteps(Routine routine, SQLiteDatabase database) {
   ContentValues values = new ContentValues();
   int stepId = this.selectMaxStepId() + 1;
   int stepOrdinal = 1;
   for (Step step : routine.getSteps()) {
     values.clear();
     values.put(DbHelper.STEP_ID, stepId);
     values.put(DbHelper.STEP_NAME, step.getName());
     values.put(DbHelper.STEP_ORDINAL, stepOrdinal);
     values.put(DbHelper.STEP_SECONDS, step.getDurationSeconds());
     values.put(DbHelper.STEP_ROUTINE_ID, routine.getId());
     stepId++;
     stepOrdinal++;
     database.insertOrThrow(DbHelper.STEPS, null, values);
   }
 }
  @Override
  public void insert(Routine newRoutine) throws Exception {
    SQLiteDatabase database = dbHelper.getWritableDatabase();

    database.beginTransaction();
    try {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK);
      Date date = new Date();
      ContentValues values = new ContentValues();
      values.put(DbHelper.ROUTINE_ID, newRoutine.getId());
      values.put(DbHelper.ROUTINE_NAME, newRoutine.getName());
      values.put(DbHelper.ROUTINE_DATE_CREATED, dateFormat.format(date));
      values.put(DbHelper.ROUTINE_DATE_UPDATED, dateFormat.format(date));
      database.insertOrThrow(DbHelper.ROUTINES, null, values);
      saveSteps(newRoutine, database);
      database.setTransactionSuccessful();
    } catch (Exception ex) {
      database.endTransaction();
      database.close();
      throw ex;
    }
    database.endTransaction();
    database.close();
  }