Beispiel #1
1
 private int deleteMessages(SQLiteDatabase db, String selection, String[] selectionArgs) {
   int count = 0;
   String sqlDesc = "";
   db.beginTransaction();
   try {
     // Delete all related records from MyDatabase.MsgOfUser for these messages
     String selectionG =
         " EXISTS ("
             + "SELECT * FROM "
             + Msg.TABLE_NAME
             + " WHERE ("
             + Msg.TABLE_NAME
             + "."
             + BaseColumns._ID
             + "="
             + MsgOfUser.TABLE_NAME
             + "."
             + MyDatabase.MsgOfUser.MSG_ID
             + ") AND ("
             + selection
             + "))";
     String descSuffix = "; args=" + Arrays.toString(selectionArgs);
     sqlDesc = selectionG + descSuffix;
     count = db.delete(MsgOfUser.TABLE_NAME, selectionG, selectionArgs);
     // Now delete messages themselves
     sqlDesc = selection + descSuffix;
     count = db.delete(Msg.TABLE_NAME, selection, selectionArgs);
     db.setTransactionSuccessful();
   } catch (Exception e) {
     MyLog.d(TAG, "; SQL='" + sqlDesc + "'", e);
   } finally {
     db.endTransaction();
   }
   return count;
 }
    @Override
    public void onUpgrade(SQLiteDatabase db, int from, int to) {
      if (from < 2) {
        db.execSQL(CREATE_HIERARCHY);
        db.beginTransaction();
        Cursor c = db.query(DICT_TABLE, null, null, null, null, null, null);
        while (!c.isLast()) {
          c.moveToNext();
          long id = c.getLong(c.getColumnIndex(DICT_COL_ID));
          ContentValues val = new ContentValues();
          val.put(HIER_COL_ANCESTOR, id);
          val.put(HIER_COL_DESCENDANT, id);
          val.put(HIER_COL_LENGTH, 0);
          db.insert(HIER_TABLE, null, val);
        }
        db.setTransactionSuccessful();
        db.endTransaction();
      }

      if (from < 3) {
        db.beginTransaction();

        ContentValues val = new ContentValues();
        val.put(VocardsDS.DICT_COL_MODIFIED, System.currentTimeMillis());
        db.update(VocardsDS.DICT_TABLE, val, VocardsDS.DICT_COL_MODIFIED + " IS NULL", null);

        db.setTransactionSuccessful();
        db.endTransaction();
      }

      if (from < 4) {
        VocardsDSMigrator.version4(db);
      }
    }
  public long addOrUpdateItem(ToDoItem toDoItem) {
    SQLiteDatabase db = getWritableDatabase();
    long id = -1;
    db.beginTransaction();
    try {
      ContentValues values = new ContentValues();
      values.put(KEY_DESCRIPTION, toDoItem.description);
      values.put(KEY_PRIORITY, toDoItem.priority);
      values.put(KEY_DUE_DATE, toDoItem.dueDate);
      values.put(KEY_MODIFIED_DATE, System.currentTimeMillis());

      if (toDoItem.action.contentEquals(CommonConstants.insertRecord)) {
        values.put(KEY_CREATED_DATE, System.currentTimeMillis());
        id = db.insertOrThrow(TABLE_TODO, null, values);
        db.setTransactionSuccessful();
      } else if (toDoItem.action.contentEquals(CommonConstants.updateRecord)) {
        id =
            db.update(
                TABLE_TODO, values, KEY_ID + " = ?", new String[] {Integer.toString(toDoItem.id)});
        db.setTransactionSuccessful();
      }
    } catch (Exception e) {
      Log.e(TAG, "Error while trying to update table. Exception is: " + e);
    } finally {
      db.endTransaction();
    }
    return id;
  }
  public int bulkInsert(Uri uri, ContentValues[] values) {
    SQLiteDatabase writeToDatabase = databaseHelper.getWritableDatabase();
    int insertedRecords = 0;
    final int match = matcher.match(uri);
    switch (match) {
      case CITY:
        writeToDatabase.beginTransaction();
        try {
          for (ContentValues value : values) {
            long insertRecord =
                writeToDatabase.insert(DatabaseContract.CityInfo.TABLE_NAME, null, value);
            if (insertRecord > 0) {
              ContentUris.withAppendedId(uri, insertRecord);
              Log.v(
                  LOG_CAT,
                  "*** Inserted City Record is: " + ContentUris.withAppendedId(uri, insertRecord));
              insertedRecords++;
            } else {
              Log.v(LOG_CAT, "*** No City records to Insert");
            }
          }
          writeToDatabase.setTransactionSuccessful();
        } finally {
          writeToDatabase.endTransaction();
        }
        getContext().getContentResolver().notifyChange(uri, null);
        break;

      case ALL_RECORDS:
        writeToDatabase.beginTransaction();
        try {
          for (ContentValues records : values) {
            long insertRecord =
                writeToDatabase.insert(DatabaseContract.ClassInfo.TABLE_NAME, null, records);
            if (insertRecord > 0) {
              ContentUris.withAppendedId(uri, insertRecord);
              Log.v(
                  LOG_CAT,
                  "*** Inserted Record is: " + ContentUris.withAppendedId(uri, insertRecord));
              insertedRecords++;
            } else {
              Log.v(LOG_CAT, "*** No records to Insert");
            }
          }
          writeToDatabase.setTransactionSuccessful();
        } finally {
          writeToDatabase.endTransaction();
        }

        getContext().getContentResolver().notifyChange(uri, null);
        break;

      default:
        return super.bulkInsert(uri, values);
    }
    return insertedRecords;
  }
 @Test
 public void testTransactionAlreadySuccessful() {
   database.beginTransaction();
   database.setTransactionSuccessful();
   try {
     database.setTransactionSuccessful();
     fail("didn't receive the expected IllegalStateException");
   } catch (IllegalStateException e) {
     assertThat(e.getMessage()).isEqualTo("transaction already successfully");
   }
 }
Beispiel #6
0
  public double[][] queryTheCursor(String startdate, String enddate) {
    double[][] result = new double[][] {};
    db.beginTransaction(); // 开始事务
    try {
      try {
        cursor =
            db.rawQuery(
                "SELECT * FROM TempTB2 WHERE _time >= ? AND _time <=?",
                new String[] {startdate, enddate});
      } catch (Exception e) {
        historyRec = "";
      }

      int count = cursor.getCount();
      if (count > 0) {
        for (int i = 0; i < count; i++) {

          cursor.moveToNext();
          historyRec +=
              "详细日期:" + cursor.getString(2) + "\r\n" + "值:" + cursor.getDouble(1) + "\r\n";
          // Yva1.add(cursor.getDouble(1));
          result[0][i] = cursor.getDouble(1);
          result[1][i] = cursor.getDouble(2);
          // cursor.moveToNext();
        }
      }
      db.setTransactionSuccessful(); // 设置事务成功完成
    } catch (Exception e) {
    } finally {
      db.endTransaction();
    }

    return result;
  }
Beispiel #7
0
 @Override
 public int bulkInsert(Uri uri, ContentValues[] values) {
   final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
   final int match = sUriMatcher.match(uri);
   switch (match) {
     case WEATHER:
       db.beginTransaction();
       int returnCount = 0;
       try {
         for (ContentValues value : values) {
           normalizeDate(value);
           long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
           if (_id != -1) {
             returnCount++;
           }
         }
         db.setTransactionSuccessful();
       } finally {
         db.endTransaction();
       }
       getContext().getContentResolver().notifyChange(uri, null);
       return returnCount;
     default:
       return super.bulkInsert(uri, values);
   }
 }
  @Override
  public int bulkInsert(Uri uri, ContentValues[] values) {

    int match = URI_MATCHER.match(uri);
    Context context = getContext();
    final SQLiteDatabase db = getDatabaseByDefaultPath(context);
    int i = 0;
    int table = match >> BASE_SHIFT;
    try {
      db.beginTransaction();
      for (ContentValues value : values) {
        switch (match) {
          case BOOKINFO:
          case BOOKMARK:
          case BOOKEMPHASIS:
            db.insert(TABLE_NAMES[table], "", value);
            break;
          default:
            throw new IllegalArgumentException(TAG + ".insert()" + ":Unknown URI" + uri);
        }

        i++;
      }
      db.setTransactionSuccessful();
    } catch (Exception e) {
      e.printStackTrace();
      i = -1;
    } finally {
      db.endTransaction();
    }
    return i;
  }
  // 添加player,如果有就更新,没有就添加。
  public void add(BubblePlayer player) {
    db.beginTransaction(); // 开始事务
    try {
      BubblePlayer personInDB = new BubblePlayer();
      personInDB = query(player.getId());

      // 如果没有找到就直接添加,如果找到了就更新
      if (null == personInDB) {
        db.execSQL(
            "INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude, headImg, sex) VALUES(?, ?, ?, ?, ?, ?)",
            new Object[] {
              player.getId(),
              player.getName(),
              player.getLatitude(),
              player.getLontitude(),
              player.getHeadImg(),
              player.getSex()
            });
      } else {
        updatePlayer(player);
      }
      db.setTransactionSuccessful(); // 设置事务成功完成
    } finally {
      db.endTransaction(); // 结束事务
    }
  }
  /**
   * Exec SQL from file in assets
   *
   * @param filename
   * @param db
   */
  protected void execSQLFile(String filename, SQLiteDatabase db) {
    // get SQL
    String sql = getSQLFromFile(filename);

    // check sql
    if (sql == null || sql.length() == 0) return;

    // split sql queries
    String[] queries = sql.split(";");

    // begin transaction
    db.beginTransaction();

    try {
      // iteratate and exec queries
      for (String query : queries) {
        db.execSQL(query);
      }

      // set transaction successful
      db.setTransactionSuccessful();
    } catch (Exception e) {
      AppLog.e(e);
    } finally {
      // end transaction
      db.endTransaction();
    }
  }
Beispiel #11
0
 /**
  * Inserts a new entry in the database, if there is no entry for the given date yet. Use this
  * method for restoring data from a backup.
  *
  * <p>This method does nothing if there is already an entry for 'date'.
  *
  * @param date the date in ms since 1970
  * @param steps the step value for 'date'; must be >= 0
  * @return true if a new entry was created, false if there was already an entry for 'date'
  */
 public boolean insertDayFromBackup(long date, int steps) {
   database.beginTransaction();
   boolean re;
   try {
     Cursor c =
         database.query(
             DB_NAME,
             new String[] {"date"},
             "date = ?",
             new String[] {String.valueOf(date)},
             null,
             null,
             null);
     re = c.getCount() == 0 && steps >= 0;
     if (re) {
       ContentValues values = new ContentValues();
       values.put("date", date);
       values.put("steps", steps);
       database.insert(DB_NAME, null, values);
     }
     c.close();
     database.setTransactionSuccessful();
   } finally {
     database.endTransaction();
   }
   return re;
 }
Beispiel #12
0
  /** update the level and count for the given flashcard in the database. */
  private void updateFlashcard(Flashcard fc) {
    openDB();

    _curDB.beginTransaction();
    try {
      // Delete old entry if any.
      SQLiteStatement dStmt = getCompiledStatement(SQL_DELETE_FCS);
      dStmt.bindString(1, fc.getLang1Str());
      dStmt.execute();

      // insert new state entry.
      SQLiteStatement iStmt = getCompiledStatement(SQL_INSERT_FCS);
      iStmt.bindString(1, fc.getLang1Str());
      iStmt.bindLong(2, fc.getLevel());
      iStmt.bindLong(3, fc.getRightGuessCount());
      iStmt.execute();
      _curDB.setTransactionSuccessful();
    } catch (SQLException e) {
      MsgDispatcher.sendMessageToUI(
          MsgType.MSG_SHOW_ERROR_MSG, 0, 0, "unable to update id=" + fc.getID());
    } finally {
      _curDB.endTransaction();
    }

    // this flashcard is no longer used by anyone so release it.
    fc.release();
  }
 private void postCorrectVerification() {
   switch (type) {
     case DATABASE:
       {
         SQLiteDatabase db = app.getDB();
         db.beginTransaction();
         ContentValues values = new ContentValues();
         Cursor cur = db.query(table, null, null, null, null, null, null);
         int index = cur.getColumnIndex("new");
         if (index >= 0) {
           values.put("new", 0);
           long result = db.update(table, values, "new = ?", new String[] {"1"});
           Log.v("mark", "postCorrectVerification set new to 0 result:" + result);
         }
         db.setTransactionSuccessful();
         db.endTransaction();
       }
       break;
     case RIGHTDRAWER:
       {
         Activity act = this.app.getCurrentActivity();
         if (act != null) {
           ((FrameActivity) act).clearRightPanel();
         }
       }
       break;
   }
   return;
 }
Beispiel #14
0
  public int update(LocalGroup group) {
    if (isNull(group)) {
      return -1;
    }

    SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
    sqLiteDatabase.beginTransaction();

    int rowsAffected = 0;
    try {
      ContentValues values = new ContentValues();
      values.put("Group_ID", group.getGroupId());
      values.put("SP_Group_ID", group.getSpGroupId());
      values.put("Remote_Group_ID", group.getRemoteGroupId());
      values.put("Group_Name", group.getName());
      long createTime = (group.getCreatedAt() == null ? 0 : group.getCreatedAt().getTime());
      values.put("Created_At", createTime);
      values.put("State", group.getState());
      values.put("Account_ID", group.getAccountId());
      rowsAffected = sqLiteDatabase.update(TABLE, values, "Group_ID = " + group.getGroupId(), null);

      sqLiteDatabase.setTransactionSuccessful();
    } finally {
      sqLiteDatabase.endTransaction();
    }

    return rowsAffected;
  }
Beispiel #15
0
  // from
  // http://stackoverflow.com/questions/3424156/upgrade-sqlite-database-from-one-version-to-another
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.beginTransaction();

    // run a table creation with if not exists (we are doing an upgrade, so the table might
    // not exists yet, it will fail alter and drop)
    db.execSQL(getManualBookmarksCreationString());
    // put in a list the existing columns
    List<String> columns = GetColumns(db, "tbl_manual_bookmarks");
    // backup table
    db.execSQL("ALTER TABLE tbl_manual_bookmarks RENAME TO 'temp_tbl_manual_bookmarks'");
    // create new table (with new scheme)
    db.execSQL(getManualBookmarksCreationString());
    // get the intersection with the new columns, this time columns taken from the upgraded table
    columns.retainAll(GetColumns(db, "tbl_manual_bookmarks"));
    // restore data
    String cols = joinStrings(columns, ",");
    db.execSQL(
        String.format(
            "INSERT INTO %s (%s) SELECT %s from 'temp_%s",
            "tbl_manual_bookmarks", cols, cols, "tbl_manual_bookmarks'"));
    // remove backup table
    db.execSQL("DROP table 'temp_tbl_manual_bookmarks'");

    db.setTransactionSuccessful();
    db.endTransaction();
  }
  public static void store(List<Category> categories) {
    if (categories == null || categories.size() == 0) {
      return;
    }

    SQLiteDatabase database = new ZhihuDatabase(App.getAppContext()).getWritableDatabase();
    database.beginTransaction();
    boolean newInsert = false;
    try {
      for (Category category : categories) {
        Cursor cursor =
            database.rawQuery(
                buildCategoryQueryUri(AppConstant.CATEGORY_EXIST_SQL, category), null);
        if (cursor == null || cursor.getCount() == 0) {
          save(category, database);
          newInsert = true;
        }
        IOUtils.close(cursor);
      }
      database.setTransactionSuccessful();
      if (newInsert) {
        App.getAppContext()
            .getContentResolver()
            .notifyChange(ZhihuProvider.CATEGORY_CONTENT_URI, null);
      }
    } catch (Exception e) {
      Timber.e(e, PersistUtils.class.getSimpleName());
    } finally {
      database.endTransaction();
    }
    // App.getAppContext().getContentResolver().notifyChange();
    IOUtils.close(database);
  }
Beispiel #17
0
  private void callUpdate(MessageEntry messageEntry) throws StorageException {
    DatabaseHelper instance = DatabaseHelper.getInstance(this);
    final SQLiteDatabase db = instance.getWritableDatabase();
    db.beginTransaction();

    try {
      CommandBusHelper.sendMessage(this, GetMessageCommand.CANCEL_UPDATE);

      // Update the database
      instance.insertOrUpdateMessage(db, messageEntry);

      Long serverId = messageEntry.getServerId();
      Long posted = messageEntry.getPosted();
      String messString = messageEntry.getMessage();

      Command command;
      if (serverId != null && posted != -1l) command = new EditMessageCommand(messString, serverId);
      else if (posted == -1l) command = new DeleteMessageCommand(serverId);
      else command = new PostMessageCommand(messString);

      CommandBusHelper.submitCommandSync(this, command);
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }
  }
 public boolean deleteAll() {
   boolean flag = false;
   String deleteHeadSql = "DELETE FROM ProductGroupHead";
   String deleteDetailSql = "DELETE FROM ProductGroupDetail";
   SQLiteDatabase db = AssetsDatabaseManager.getManager().getDatabase();
   try {
     // 开启事务
     db.beginTransaction();
     SQLiteStatement detail_stat = db.compileStatement(deleteDetailSql);
     detail_stat.executeUpdateDelete();
     SQLiteStatement head_stat = db.compileStatement(deleteHeadSql);
     head_stat.executeUpdateDelete();
     // 数据插入成功,设置事物成功标志
     db.setTransactionSuccessful();
     // 保存数据
     db.endTransaction();
     flag = true;
   } catch (SQLException e) {
     // 结束事物,在这里没有设置成功标志,结束后不保存
     ZillionLog.e(this.getClass().getName(), e.getMessage(), e);
     db.endTransaction();
     e.printStackTrace();
   }
   return flag;
 }
Beispiel #19
0
  @Override
  public void bulkUpdate(
      String tableName,
      List<ContentValues> contentValuesList,
      String key,
      List<Integer> deleteList) {
    long id;
    try {
      if (database == null) {
        database = helper.getWritableDatabase();
      }
      for (ContentValues values : contentValuesList) {
        id = database.replace(tableName, null, values);
        if (id == -1) {
          CommonLog.e(CLASSTAG, "bulk update err, value: " + values.toString());
        }
      }

      for (int values : deleteList) {
        database.execSQL("DELETE FROM " + tableName + " WHERE " + key + " = " + values);
      }
      database.setTransactionSuccessful();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (database != null) {
        database.endTransaction();
      }
    }
  }
  private void maybeAddBulletin(BulletinResponse bltn) {
    maybeAddBlockRef(bltn.blockReference);

    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
      ContentValues values = new ContentValues();
      values.put(NewBltnsTable.COLUMN_TXID, bltn.txid);
      values.put(NewBltnsTable.COLUMN_TIME, bltn.timestamp);
      values.put(NewBltnsTable.COLUMN_MSG, bltn.msg);
      values.put(NewBltnsTable.COLUMN_LAT, bltn.loc.lat);
      values.put(NewBltnsTable.COLUMN_LON, bltn.loc.lon);
      values.put(NewBltnsTable.COLUMN_H, bltn.loc.h);
      values.put(NewBltnsTable.COLUMN_AUTHOR, bltn.author);
      values.put(NewBltnsTable.COLUMN_NUM_ENDOS, bltn.numEndos);
      values.put(NewBltnsTable.COLUMN_BLOCK_REF, bltn.blockReference.hash);

      db.insertOrThrow(NewBltnsTable.TABLE_NAME, null, values);
      db.setTransactionSuccessful();

    } catch (Exception e) {

    } finally {
      db.endTransaction();
    }
  }
Beispiel #21
0
  public void insertInTable(ArrayList<ArchivoMp3> ListaMp3) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    db.beginTransaction();
    try {
      for (ArchivoMp3 Mp3 : ListaMp3) {

        values.put("imagen", Mp3.getCaratula());
        values.put("artista", Mp3.getBanda());
        values.put("album", Mp3.getAlbum());
        values.put("cancion", Mp3.getTitulo());
        values.put("duracion", Mp3.getDuracion());
        values.put("genero", Mp3.getGenero());
        values.put("ruta", Mp3.getRuta());
        values.put("id_cancion", Mp3.getCancionId());
        db.insert("rolas", null, values);
      }

      // db.yieldIfContendedSafely(); //keeps the table from locking
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }

    db.close();
  }
  public void nextInstruction(boolean isSucessful, int intented_nextId) {
    SQLiteDatabase db = app.getDB();
    db.beginTransaction();
    // deal with current Instruction
    if (current != null) {
      markCurrentInstructionState(
          db, current._id, isSucessful ? Instruction.COMPLETED : Instruction.SKIPPED);
      intented_nextId = current._id + 1;
    }
    Instruction nextInstruction = fetchNextInstruction(db, intented_nextId);
    if (nextInstruction != null) { // check has nextTask
      // check if in the same task
      if (current == null || current.task_id != nextInstruction.task_id) {
        // app.enterNewTask(current, nextInstruction);
        app.enterNewTask(nextInstruction.task_id);
      }
      boolean switchSegment = (current == null) ? false : (nextInstruction.seg_id > current.seg_id);

      current = nextInstruction;
      app.setUserInfomraiton(
          null, nextInstruction._id, nextInstruction.task_id, nextInstruction.seg_id);

      if (switchSegment) app.onChangeSegment();
      //			Log.v("mark", "nextInstruction id:" + nextInstruction);
    } else { // no more instruction
      app.enterNewTask(-1);
      // app.enterNewTask(current, null);
      current = null;
      Log.v("mark", "nextInstruction is null");
      app.onAllTaskFinished();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
  }
Beispiel #23
0
  /** Insert a set of flashcards (linked list) in a single transaction. */
  private void insertFlashcardSet(Flashcard head) {
    openDB();
    SQLiteStatement stmt = getCompiledStatement(SQL_INSERT_FC);
    boolean gotError = false;

    _curDB.beginTransaction();
    try {
      for (Flashcard fc = head; fc != null; fc = Flashcard.Chain.getNext(fc)) {

        stmt.bindLong(1, _importState.getRandomId());
        stmt.bindString(2, fc.getLang1Str());
        stmt.bindString(3, fc.getLang2Str());
        stmt.execute();
      }
      _curDB.setTransactionSuccessful();
    } catch (SQLException e) {
      gotError = true;
      MsgDispatcher.sendMessageToUI(MsgType.MSG_SHOW_ERROR_MSG, 0, 0, "unable to insert fc");
    } finally {
      _curDB.endTransaction();
    }

    Flashcard.Chain.releaseChain(head);

    // tell controller to send us more data if insert went fine.
    if (!gotError) {
      MsgDispatcher.sendMessageToController(MsgType.MSG_CONTINUE_IMPORT, 0, 0, null);
    }
  }
Beispiel #24
0
 private long update(SQLiteDatabase db, Pista pista) {
   db.beginTransaction();
   try {
     // save pista
     int row =
         db.update(
             TABLE,
             getContentValues(pista),
             Columns._UUID.getColumnName() + " = ? ",
             new String[] {pista.getUuid()});
     // save local
     pista.getLocal().setUuidLocalizavel(pista.getUuid());
     localDAO.save(db, pista.getLocal());
     // save horario
     pista.getHorario().setUuidLocalizavel(pista.getUuid());
     horarioDAO.save(db, pista.getHorario());
     // save esportes
     localizavelEsporteDAO.save(db, pista.getUuid(), pista.getEsportes());
     db.setTransactionSuccessful();
     return row;
   } catch (Exception ex) {
     Log.e(TAG, "Error updating pista.", ex);
   } finally {
     db.endTransaction();
   }
   return -1;
 }
Beispiel #25
0
  /**
   * Inserts a new entry in the database, if there is no entry for the given date yet. Steps should
   * be the current number of steps and it's negative value will be used as offset for the new date.
   * Also adds 'steps' steps to the previous day, if there is an entry for that date.
   *
   * <p>This method does nothing if there is already an entry for 'date' - use {@link #updateSteps}
   * in this case.
   *
   * <p>To restore data from a backup, use {@link #insertDayFromBackup}
   *
   * @param date the date in ms since 1970
   * @param steps the current step value to be used as negative offset for the new day; must be >= 0
   */
  public void insertNewDay(long date, int steps) {
    database.beginTransaction();
    try {
      Cursor c =
          database.query(
              DB_NAME,
              new String[] {"date"},
              "date = ?",
              new String[] {String.valueOf(date)},
              null,
              null,
              null);
      if (c.getCount() == 0 && steps >= 0) {
        ContentValues values = new ContentValues();
        values.put("date", date);
        // use the negative steps as offset
        values.put("steps", -steps);
        database.insert(DB_NAME, null, values);

        // add 'steps' to yesterdays count
        date -= 24 * 60 * 60 * 1000;
        updateSteps(date, steps);
      }
      c.close();
      if (Logger.LOG) {
        Logger.log("insertDay " + date + " / " + steps);
        logState();
      }
      database.setTransactionSuccessful();
    } finally {
      database.endTransaction();
    }
  }
  @Override
  public void addGBActivitySamples(ActivitySample[] activitySamples) {
    try (SQLiteDatabase db = this.getWritableDatabase()) {

      String sql =
          "INSERT INTO "
              + TABLE_GBACTIVITYSAMPLES
              + " ("
              + KEY_TIMESTAMP
              + ","
              + KEY_PROVIDER
              + ","
              + KEY_INTENSITY
              + ","
              + KEY_STEPS
              + ","
              + KEY_TYPE
              + ")"
              + " VALUES (?,?,?,?,?);";
      SQLiteStatement statement = db.compileStatement(sql);
      db.beginTransaction();

      for (ActivitySample activitySample : activitySamples) {
        statement.clearBindings();
        statement.bindLong(1, activitySample.getTimestamp());
        statement.bindLong(2, activitySample.getProvider().getID());
        statement.bindLong(3, activitySample.getRawIntensity());
        statement.bindLong(4, activitySample.getSteps());
        statement.bindLong(5, activitySample.getRawKind());
        statement.execute();
      }
      db.setTransactionSuccessful();
      db.endTransaction();
    }
  }
 /** add persons */
 public void add(List<BubblePlayer> bubbleplayers) {
   db.beginTransaction(); // 开始事务
   try {
     for (BubblePlayer player : bubbleplayers) {
       // db.execSQL("INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude ) VALUES(5,
       // 'name', 31, 130)");
       BubblePlayer personInDB = new BubblePlayer();
       personInDB = query(player.getId());
       if (null == personInDB) {
         db.execSQL(
             "INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude, headImg, sex) VALUES(?, ?, ?, ?, ?, ?)",
             new Object[] {
               player.getId(),
               player.getName(),
               player.getLatitude(),
               player.getLontitude(),
               player.getHeadImg(),
               player.getSex()
             });
       } else {
         updatePlayer(player);
       }
     }
     db.setTransactionSuccessful(); // 设置事务成功完成
   } finally {
     db.endTransaction(); // 结束事务
   }
 }
  /**
   * Removes rows in the smartdial database that matches the contacts that have been deleted by
   * other apps since last update.
   *
   * @param db Database pointer to the dialer database.
   * @param last_update_time Time stamp of last update on the smartdial database
   */
  private void removeDeletedContacts(SQLiteDatabase db, String last_update_time) {
    final Cursor deletedContactCursor =
        mContext
            .getContentResolver()
            .query(
                DeleteContactQuery.URI,
                DeleteContactQuery.PROJECTION,
                DeleteContactQuery.SELECT_UPDATED_CLAUSE,
                new String[] {last_update_time},
                null);

    db.beginTransaction();
    try {
      while (deletedContactCursor.moveToNext()) {
        final Long deleteContactId =
            deletedContactCursor.getLong(DeleteContactQuery.DELETED_CONTACT_ID);
        db.delete(
            Tables.SMARTDIAL_TABLE, SmartDialDbColumns.CONTACT_ID + "=" + deleteContactId, null);
        db.delete(Tables.PREFIX_TABLE, PrefixColumns.CONTACT_ID + "=" + deleteContactId, null);
      }

      db.setTransactionSuccessful();
    } finally {
      deletedContactCursor.close();
      db.endTransaction();
    }
  }
  public void fillInitialDish() {
    String cooking =
        "Салатные листья замочить в холодной воде на 1 час, чтобы они стали свежими и хрустящими.\n"
            + "Белый хлеб очистить от корочки и порезать на кубики размером примерно 1 сантиметр, затем выложить на противень и подсушить в не слишком горячей духовке.\n"
            + "В глубокую сковороду налить растительное масло, положить измельченный чеснок. Как только кусочки потемнеют, снять их со сковороды и выложить в масло сухарики. Обжарить до золотистой корочки, выложить на бумажную салфетку для удаления лишнего масла.\n"
            + "Куриное филе натереть солью и обжарить до готовности, затем остудить и порезать тонкими пластинками.\n"
            + "Листья салата порвать руками, сыр нарезать тонкими пластинками. Помидоры черри разрезать на четыре части.\n"
            + "Выложить в салатник все ингредиенты, слегка встряхнуть, чтобы они перемешались, и сразу же подать на стол. Майонез подать отдельно, чтобы каждый едок мог добавлять его по вкусу.";
    if (db != null) {
      try {
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put(Dish.COLUMN_TITLE, "Салат \"Цезарь\" с курицей и сухариками");
        values.put(Dish.COLUMN_COOKING, cooking);
        values.put(Dish.COLUMN_CELEBRATORY, true);
        values.put(Dish.COLUMN_KIND_ID, 3);
        db.insert(Dish.TABLE_NAME, null, values);
        db.setTransactionSuccessful();

        Log.i(LOG_TAG, "Dish table filled");
      } catch (SQLiteException e) {
        Log.e(LOG_TAG, e.getMessage());
      } finally {
        db.endTransaction();
      }
    }
  }
  @Override
  public int bulkInsert(Uri uri, ContentValues[] values) {
    // Resolve the URI.
    int match = mUriMatcher.match(uri);
    Mapping mapping = match != UriMatcher.NO_MATCH ? mMappings.get(match) : null;
    if (mapping == null || mapping.hasId) {
      throw new IllegalArgumentException("Invalid URI: " + uri);
    }

    // Insert all rows into the database and notify observers.
    String tableName = mapping.table.getTableName();
    SQLiteDatabase database = mDatabase.getWritableDatabase();
    int numInserted = 0;
    try {
      int length = values.length;
      database.beginTransaction();
      for (int i = 0; i != length; ++i) {
        database.insert(tableName, NULL_COLUMN_HACK, values[i]);
      }
      database.setTransactionSuccessful();
      numInserted = length;
    } finally {
      database.endTransaction();
    }
    notifyChange(uri);
    return numInserted;
  }