@Test
 public void testInTransaction() throws Exception {
   assertThat(database.inTransaction()).isFalse();
   database.beginTransaction();
   assertThat(database.inTransaction()).isTrue();
   database.endTransaction();
   assertThat(database.inTransaction()).isFalse();
 }
 public void setAutoCommit(boolean autoCommit) {
   /*
    * Sqlite does not support auto-commit. The various JDBC drivers seem to implement it with the use of a
    * transaction. That's what we are doing here.
    */
   if (autoCommit) {
     if (db.inTransaction()) {
       db.setTransactionSuccessful();
       db.endTransaction();
     }
   } else {
     if (!db.inTransaction()) {
       db.beginTransaction();
     }
   }
 }
Ejemplo n.º 3
0
  // 批量插入数据点
  int bulkInsertWaypoint(long trackId, long segmentId, ContentValues[] valuesArray) {
    if (trackId < 0 || segmentId < 0) {
      throw new IllegalArgumentException("Track and segments may not the less then 0.");
    }
    int inserted = 0;

    SQLiteDatabase sqldb = getWritableDatabase();
    sqldb.beginTransaction();
    try {
      for (ContentValues args : valuesArray) {
        args.put(Waypoints.SEGMENT, segmentId);

        long id = sqldb.insert(Waypoints.TABLE, null, args);
        if (id >= 0) {
          inserted++;
        }
      }
      sqldb.setTransactionSuccessful();

    } finally {
      if (sqldb.inTransaction()) {
        sqldb.endTransaction();
      }
    }

    return inserted;
  }
 public boolean isAutoCommit() throws SQLException {
   try {
     boolean inTransaction = db.inTransaction();
     logger.trace("{}: in transaction is {}", this, inTransaction);
     // You have to explicitly commit your transactions, so this is sort of correct
     return !inTransaction;
   } catch (android.database.SQLException e) {
     throw SqlExceptionUtil.create("problems getting auto-commit from database", e);
   }
 }
Ejemplo n.º 5
0
  /**
   * 添加登录信息
   *
   * @param loginInfo
   * @return
   */
  public boolean addLoginInfo(UserInfo loginInfo) {
    Logger.i(LoginInfoDao.class, "[登录信息数据操作类]:添加用户登录信息");
    SQLiteDatabase db = null;
    try {
      db = databaseHelper.getWritableDatabase();
      if (loginInfo != null) {
        // 开启事务
        db.beginTransaction();
        // 为保证数据只有一条,添加之前先进行删除
        db.delete(LoginInfoTable.Table_Name, null, null);
        ContentValues values = new ContentValues();

        values.put(LoginInfoTable.AccessToken, loginInfo.AccessToken);
        values.put(LoginInfoTable.ExpiresIn, loginInfo.ExpiresIn);
        values.put(LoginInfoTable.RefreshToken, loginInfo.RefreshToken);

        values.put(LoginInfoTable.Id, loginInfo.Id);
        values.put(LoginInfoTable.Code, loginInfo.Code);
        values.put(LoginInfoTable.Name, loginInfo.Name);

        values.put(LoginInfoTable.NameShort, loginInfo.NameShort);
        values.put(LoginInfoTable.BelongArea, loginInfo.BelongArea.value());
        values.put(LoginInfoTable.Sex, loginInfo.Sex.value());

        values.put(LoginInfoTable.Phone, loginInfo.Phone);
        values.put(LoginInfoTable.Photo, loginInfo.Photo);
        values.put(LoginInfoTable.Department, loginInfo.Department);

        values.put(LoginInfoTable.EipPhone, loginInfo.EipPhone);
        values.put(LoginInfoTable.BindPhone, loginInfo.BindPhone);
        values.put(LoginInfoTable.DefaultPassword, loginInfo.DefaultPassword);

        /* 插入数据库操作 */
        db.insert(LoginInfoTable.Table_Name, null, values);
        // 关闭事务
        db.setTransactionSuccessful();
      }
      return true;
    } catch (Exception e) {
      Logger.e(LoginInfoDao.class, "[登录信息数据操作类]:添加用户信息异常:", e);
      return false;
    } finally {
      if (db != null) {
        if (db.inTransaction()) {
          db.endTransaction();
        }
        db.close();
      }
    }
  }
Ejemplo n.º 6
0
 public static void addAmbient(SQLiteDatabase db, AmbientDB a) {
   try {
     db.beginTransaction();
     SQLiteStatement stmt = db.compileStatement(AmbientDB.INSERT_SQL);
     stmt.clearBindings();
     stmt.bindString(1, a.ambientId);
     stmt.bindDouble(2, a.temperature);
     stmt.bindLong(3, a.light);
     stmt.execute();
     stmt.close();
     db.setTransactionSuccessful();
   } finally {
     if (db.inTransaction()) {
       db.endTransaction();
     }
   }
 }
Ejemplo n.º 7
0
 public static void updateAmbient(SQLiteDatabase db, ArrayList<AmbientDB> aList) {
   try {
     db.beginTransaction();
     SQLiteStatement stmt = db.compileStatement(AmbientDB.UPDATE_SQL);
     for (int n = 0; n < aList.size(); n++) {
       AmbientDB u = aList.get(n);
       stmt.clearBindings();
       stmt.bindString(3, u.ambientId);
       stmt.bindDouble(1, u.temperature);
       stmt.bindLong(2, u.light);
       stmt.execute();
     }
     stmt.close();
     db.setTransactionSuccessful();
   } finally {
     if (db.inTransaction()) {
       db.endTransaction();
     }
   }
 }
Ejemplo n.º 8
0
  private void processFile(File doc, Importer importer) {
    InputPositionReader posRdr;
    CSVReader rdr;
    try {
      posRdr = new InputPositionReader(new FileReader(doc));
      rdr = new CSVReader(posRdr, CSV_SEPARATOR);
    } catch (FileNotFoundException e) {
      // Shouldn't occur, because the caller checks for existence
      e.printStackTrace();
      return;
    }

    reportProgress(0);
    EGODbHelper helper = new EGODbHelper(getBaseContext(), false);
    db = helper.getWritableDatabase();
    if (db == null) {
      reportError(getResources().getString(R.string.error_db_object_null));
      return;
    }

    db.beginTransaction();
    importer.setDatabase(db);
    importer.preProcess();

    try {
      long fileLength = doc.length();
      double lastPercent = 0;
      int numEntries = 0;
      int failedEntries = 0;

      String[] fields = rdr.readNext();
      fields[0] =
          fields[0].replace(
              "\uFEFF", ""); // Replace UTF-8 BOM in first field of the file if it exists
      while (fields != null) {
        if (fields.length > 0 && !fields[0].startsWith(CSV_COMMENT)) {
          int result = importer.process(fields);
          if (result != Importer.PROCESS_IGNORED) {
            numEntries++;
            if (result == Importer.PROCESS_ERROR) {
              failedEntries++;
            }
          }
        }

        // Because BufferedReader reads chunks from the file, line lengths don't correlate with file
        // position
        double newPercent = posRdr.getPosition() / (double) fileLength;
        if (newPercent > lastPercent) {
          lastPercent = newPercent;
          reportProgress(lastPercent);
        }
        fields = rdr.readNext();
      }

      rdr.close();
      db.setTransactionSuccessful();
      db.endTransaction();

      reportResultImport(numEntries - failedEntries, failedEntries);
      importer.postProcess();
    } catch (IOException e) {
      reportError(getResources().getString(R.string.service_dataimport_error_readfail));
    } finally {
      try {
        rdr.close();
      } catch (Exception e) {
      }

      if (db.inTransaction()) {
        db.endTransaction();
      }
      db.close();
    }
  }
Ejemplo n.º 9
0
  /**
   * Deletes a single track and all underlying segments, waypoints, media and metadata
   *
   * @param trackId
   * @return
   */
  int deleteTrack(long trackId) {
    SQLiteDatabase sqldb = getWritableDatabase();
    int affected = 0;
    Cursor cursor = null;
    long segmentId = -1;
    long metadataId = -1;

    try {
      sqldb.beginTransaction();
      // Iterate on each segement to delete each
      cursor =
          sqldb.query(
              Segments.TABLE,
              new String[] {Segments._ID},
              Segments.TRACK + "= ?",
              new String[] {String.valueOf(trackId)},
              null,
              null,
              null,
              null);
      if (cursor.moveToFirst()) {
        do {
          segmentId = cursor.getLong(0);
          affected += deleteSegment(sqldb, trackId, segmentId);
        } while (cursor.moveToNext());
      } else {
        Log.e(TAG, "Did not find the last active segment");
      }
      // Delete the track
      affected +=
          sqldb.delete(Tracks.TABLE, Tracks._ID + "= ?", new String[] {String.valueOf(trackId)});
      // Delete remaining meta-data
      affected +=
          sqldb.delete(
              MetaData.TABLE, MetaData.TRACK + "= ?", new String[] {String.valueOf(trackId)});

      cursor =
          sqldb.query(
              MetaData.TABLE,
              new String[] {MetaData._ID},
              MetaData.TRACK + "= ?",
              new String[] {String.valueOf(trackId)},
              null,
              null,
              null,
              null);
      if (cursor.moveToFirst()) {
        do {
          metadataId = cursor.getLong(0);
          affected += deleteMetaData(metadataId);
        } while (cursor.moveToNext());
      }

      sqldb.setTransactionSuccessful();
    } finally {
      if (cursor != null) {
        cursor.close();
      }
      if (sqldb.inTransaction()) {
        sqldb.endTransaction();
      }
    }

    ContentResolver resolver = this.mContext.getContentResolver();
    resolver.notifyChange(Tracks.CONTENT_URI, null);
    resolver.notifyChange(ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId), null);

    return affected;
  }
Ejemplo n.º 10
0
  @Override
  protected void onHandleIntent(Intent intent) {
    final boolean force = intent.getBooleanExtra("force", false);
    try {
      Locale loc = Locale.getDefault();
      String lang =
          loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php;
      // T-values if present both T and B
      if (lang == null || lang.length() == 0) {
        lang = "";
      }

      int serverVersion = intent.getIntExtra("serverVersion", -1);
      boolean fromPush = serverVersion != -1;
      JSONObject versionJson = null;
      if (!fromPush) {
        versionJson = getVersion(true);
        serverVersion = versionJson.getInt("version");
      }
      int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1);
      final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, "");

      if (serverVersion <= localVersion
          && !force
          && lang.equals(localLanguage)
          && !LOCAL_DEFINITION_TESTING) {
        // don't update
        DebugLog.i("Nothing new, not updating");
        return;
      }

      // update but don't notify about it.
      boolean firstLaunchNoUpdate =
          ((localVersion == -1 && getVersion(false).getInt("version") == serverVersion)
              || !lang.equals(localLanguage));

      if (!firstLaunchNoUpdate) {
        DebugLog.i("There are new definitions available!");
      }

      handleAuthorMessage(versionJson, lang, intent, fromPush);

      InputStream is = getIS(URL_TICKETS_ID);
      try {
        String json = readResult(is);

        JSONObject o = new JSONObject(json);
        JSONArray array = o.getJSONArray("tickets");

        final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase();
        for (int i = 0; i < array.length(); i++) {
          final JSONObject city = array.getJSONObject(i);
          try {

            final ContentValues cv = new ContentValues();
            cv.put(Cities._ID, city.getInt("id"));
            cv.put(Cities.CITY, getStringLocValue(city, lang, "city"));
            if (city.has("city_pubtran")) {
              cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran"));
            }
            cv.put(Cities.COUNTRY, city.getString("country"));
            cv.put(Cities.CURRENCY, city.getString("currency"));
            cv.put(Cities.DATE_FORMAT, city.getString("dateFormat"));
            cv.put(Cities.IDENTIFICATION, city.getString("identification"));
            cv.put(Cities.LAT, city.getDouble("lat"));
            cv.put(Cities.LON, city.getDouble("lon"));
            cv.put(Cities.NOTE, getStringLocValue(city, lang, "note"));
            cv.put(Cities.NUMBER, city.getString("number"));
            cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom"));
            cv.put(Cities.P_DATE_TO, city.getString("pDateTo"));
            cv.put(Cities.P_HASH, city.getString("pHash"));
            cv.put(Cities.PRICE, city.getString("price"));
            cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote"));
            cv.put(Cities.REQUEST, city.getString("request"));
            cv.put(Cities.VALIDITY, city.getInt("validity"));
            if (city.has("confirmReq")) {
              cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq"));
            }
            if (city.has("confirm")) {
              cv.put(Cities.CONFIRM, city.getString("confirm"));
            }

            final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers");
            for (int j = 0; j < additionalNumbers.length() && j < 3; j++) {
              cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j));
            }

            db.beginTransaction();
            int count =
                db.update(
                    DatabaseHelper.CITY_TABLE_NAME,
                    cv,
                    Cities._ID + " = " + cv.getAsInteger(Cities._ID),
                    null);
            if (count == 0) {
              db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv);
            }

            db.setTransactionSuccessful();
            getContentResolver().notifyChange(Cities.CONTENT_URI, null);
          } finally {
            if (db.inTransaction()) {
              db.endTransaction();
            }
          }
        }
        Preferences.set(c, Preferences.DATA_VERSION, serverVersion);
        Preferences.set(c, Preferences.DATA_LANGUAGE, lang);
        if (!firstLaunchNoUpdate && !fromPush) {
          final int finalServerVersion = serverVersion;
          mHandler.post(
              new Runnable() {
                @Override
                public void run() {
                  Toast.makeText(
                          UpdateService.this,
                          getString(R.string.cities_update_completed, finalServerVersion),
                          Toast.LENGTH_LONG)
                      .show();
                }
              });
        }
        if (LOCAL_DEFINITION_TESTING) {
          DebugLog.w(
              "Local definition testing - data updated from assets - must be removed in production!");
        }
      } finally {
        is.close();
      }
    } catch (IOException e) {
      DebugLog.e("IOException when calling update: " + e.getMessage(), e);
    } catch (JSONException e) {
      DebugLog.e("JSONException when calling update: " + e.getMessage(), e);
    }
  }