Esempio n. 1
0
 public void deleteTran(Account acct, String transID) {
   String[] args = {Integer.toString(acct.ID), transID};
   db.beginTransaction();
   try {
     db.delete("trans", "acct_id=? and trans_id=?", args);
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
 }
Esempio n. 2
0
 private void updateTran(Transaction trans) {
   db.beginTransaction();
   try {
     ContentValues newValue = tranValues(trans);
     String[] args = {Integer.toString(trans.ID)};
     db.update("trans", newValue, "_id=?", args);
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
 }
Esempio n. 3
0
 private void updateAccount(Account acct) {
   db.beginTransaction();
   try {
     ContentValues newValue = acctValues(acct);
     String[] args = {Integer.toString(acct.ID)};
     db.update("acct", newValue, "_id=?", args);
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
 }
Esempio n. 4
0
 private int addAccount(Account acct) {
   db.beginTransaction();
   int acct_id;
   try {
     ContentValues newValue = acctValues(acct);
     acct_id = (int) db.insertOrThrow("acct", "name", newValue);
     acct.ID = acct_id;
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
   return acct_id;
 }
Esempio n. 5
0
  private int addTran(Transaction trans) {
    db.beginTransaction();
    int tran_id;
    try {
      ContentValues newValue = tranValues(trans);
      tran_id = (int) db.insertOrThrow("trans", "acct_id", newValue);
      trans.ID = tran_id;

      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }
    return tran_id;
  }
  /**
   * Executes a batch request and sends the results via sendJavascriptCB().
   *
   * @param dbname The name of the database.
   * @param queryarr Array of query strings
   * @param jsonparams Array of JSON query parameters
   * @param queryIDs Array of query ids
   * @param cbc Callback context from Cordova API
   */
  private void executeSqlBatch(
      String dbname,
      String[] queryarr,
      JSONArray[] jsonparams,
      String[] queryIDs,
      CallbackContext cbc) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null) return;

    String query = "";
    String query_id = "";
    int len = queryarr.length;

    JSONArray batchResults = new JSONArray();

    for (int i = 0; i < len; i++) {
      query_id = queryIDs[i];

      JSONObject queryResult = null;
      String errorMessage = "unknown";

      try {
        boolean needRawQuery = true;

        query = queryarr[i];

        // UPDATE or DELETE:
        // NOTE: this code should be safe to RUN with old Android SDK.
        // To BUILD with old Android SDK remove lines from HERE: {{
        if (android.os.Build.VERSION.SDK_INT >= 11
            && (query.toLowerCase().startsWith("update")
                || query.toLowerCase().startsWith("delete"))) {
          SQLiteStatement myStatement = mydb.compileStatement(query);

          if (jsonparams != null) {
            for (int j = 0; j < jsonparams[i].length(); j++) {
              if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
              } else if (jsonparams[i].get(j) instanceof Number) {
                myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
              } else if (jsonparams[i].isNull(j)) {
                myStatement.bindNull(j + 1);
              } else {
                myStatement.bindString(j + 1, jsonparams[i].getString(j));
              }
            }
          }

          int rowsAffected = -1; // (assuming invalid)

          // Use try & catch just in case android.os.Build.VERSION.SDK_INT >= 11 is lying:
          try {
            rowsAffected = myStatement.executeUpdateDelete();
            // Indicate valid results:
            needRawQuery = false;
          } catch (SQLiteException ex) {
            // Indicate problem & stop this query:
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v(
                "executeSqlBatch", "SQLiteStatement.executeUpdateDelete(): Error=" + errorMessage);
            needRawQuery = false;
          } catch (Exception ex) {
            // Assuming SDK_INT was lying & method not found:
            // do nothing here & try again with raw query.
          }

          if (rowsAffected != -1) {
            queryResult = new JSONObject();
            queryResult.put("rowsAffected", rowsAffected);
          }
        } // to HERE. }}

        // INSERT:
        if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
          needRawQuery = false;

          SQLiteStatement myStatement = mydb.compileStatement(query);

          for (int j = 0; j < jsonparams[i].length(); j++) {
            if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
              myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
            } else if (jsonparams[i].get(j) instanceof Number) {
              myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
            } else if (jsonparams[i].isNull(j)) {
              myStatement.bindNull(j + 1);
            } else {
              myStatement.bindString(j + 1, jsonparams[i].getString(j));
            }
          }

          long insertId = -1; // (invalid)

          try {
            insertId = myStatement.executeInsert();
          } catch (SQLiteException ex) {
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v("executeSqlBatch", "SQLiteDatabase.executeInsert(): Error=" + errorMessage);
          }

          if (insertId != -1) {
            queryResult = new JSONObject();
            queryResult.put("insertId", insertId);
            queryResult.put("rowsAffected", 1);
          }
        }

        if (query.toLowerCase().startsWith("begin")) {
          needRawQuery = false;
          try {
            mydb.beginTransaction();

            queryResult = new JSONObject();
            queryResult.put("rowsAffected", 0);
          } catch (SQLiteException ex) {
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v("executeSqlBatch", "SQLiteDatabase.beginTransaction(): Error=" + errorMessage);
          }
        }

        if (query.toLowerCase().startsWith("commit")) {
          needRawQuery = false;
          try {
            mydb.setTransactionSuccessful();
            mydb.endTransaction();

            queryResult = new JSONObject();
            queryResult.put("rowsAffected", 0);
          } catch (SQLiteException ex) {
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v(
                "executeSqlBatch",
                "SQLiteDatabase.setTransactionSuccessful/endTransaction(): Error=" + errorMessage);
          }
        }

        if (query.toLowerCase().startsWith("rollback")) {
          needRawQuery = false;
          try {
            mydb.endTransaction();

            queryResult = new JSONObject();
            queryResult.put("rowsAffected", 0);
          } catch (SQLiteException ex) {
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v("executeSqlBatch", "SQLiteDatabase.endTransaction(): Error=" + errorMessage);
          }
        }

        // raw query for other statements:
        if (needRawQuery) {
          String[] params = null;

          if (jsonparams != null) {
            params = new String[jsonparams[i].length()];

            for (int j = 0; j < jsonparams[i].length(); j++) {
              if (jsonparams[i].isNull(j)) params[j] = "";
              else params[j] = jsonparams[i].getString(j);
            }
          }

          Cursor myCursor = mydb.rawQuery(query, params);

          if (query_id.length() > 0) {
            queryResult = this.getRowsResultFromQuery(myCursor);
          }

          myCursor.close();
        }
      } catch (Exception ex) {
        ex.printStackTrace();
        errorMessage = ex.getMessage();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage);
      }

      try {
        if (queryResult != null) {
          JSONObject r = new JSONObject();
          r.put("qid", query_id);

          r.put("type", "success");
          r.put("result", queryResult);

          batchResults.put(r);
        } else {
          JSONObject r = new JSONObject();
          r.put("qid", query_id);
          r.put("type", "error");

          JSONObject er = new JSONObject();
          er.put("message", errorMessage);
          r.put("result", er);

          batchResults.put(r);
        }
      } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + ex.getMessage());
        // TODO what to do?
      }
    }

    cbc.success(batchResults);
  }
  /**
   * Create and/or open a database that will be used for reading and writing. The first time this is
   * called, the database will be opened and {@link #onCreate}, {@link #onUpgrade} and/or {@link
   * #onOpen} will be called.
   *
   * <p>Once opened successfully, the database is cached, so you can call this method every time you
   * need to write to the database. (Make sure to call {@link #close} when you no longer need the
   * database.) Errors such as bad permissions or a full disk may cause this method to fail, but
   * future attempts may succeed if the problem is fixed.
   *
   * <p class="caution">Database upgrade may take a long time, you should not call this method from
   * the application main thread, including from {@link android.content.ContentProvider#onCreate
   * ContentProvider.onCreate()}.
   *
   * @throws SQLiteException if the database cannot be opened for writing
   * @return a read/write database object valid until {@link #close} is called
   */
  public synchronized SQLiteDatabase getWritableDatabase() {
    if (mDatabase != null) {
      if (!mDatabase.isOpen()) {
        // darn! the user closed the database by calling mDatabase.close()
        mDatabase = null;
      } else if (!mDatabase.isReadOnly()) {
        return mDatabase; // The database is already open for business
      }
    }

    if (mIsInitializing) {
      throw new IllegalStateException("getWritableDatabase called recursively");
    }

    // If we have a read-only database open, someone could be using it
    // (though they shouldn't), which would cause a lock to be held on
    // the file, and our attempts to open the database read-write would
    // fail waiting for the file lock.  To prevent that, we acquire the
    // lock on the read-only database, which shuts out other users.

    boolean success = false;
    SQLiteDatabase db = null;
    if (mDatabase != null) mDatabase.lock();
    try {
      mIsInitializing = true;
      if (mName == null) {
        db = SQLiteDatabase.create(null);
      } else {
        db =
            SQLiteDatabase.openDatabase(
                mName, mPasswd, mFactory,
                0); // mContext.openOrCreateDatabase(mName, 0, mFactory, mErrorHandler);
      }

      int version = db.getVersion();
      if (version != mNewVersion) {
        db.beginTransaction();
        try {
          if (version == 0) {
            onCreate(db);
          } else {
            if (version > mNewVersion) {
              onDowngrade(db, version, mNewVersion);
            } else {
              onUpgrade(db, version, mNewVersion);
            }
          }
          db.setVersion(mNewVersion);
          db.setTransactionSuccessful();
        } finally {
          db.endTransaction();
        }
      }

      onOpen(db);
      success = true;
      return db;
    } finally {
      mIsInitializing = false;
      if (success) {
        if (mDatabase != null) {
          try {
            mDatabase.close();
          } catch (Exception e) {
          }
          mDatabase.unlock();
        }
        mDatabase = db;
      } else {
        if (mDatabase != null) mDatabase.unlock();
        if (db != null) db.close();
      }
    }
  }
  private SQLiteDatabase getDatabaseLocked(boolean writable) {
    if (mDatabase != null) {
      if (!mDatabase.isOpen()) {
        // Darn!  The user closed the database by calling mDatabase.close().
        mDatabase = null;
      } else if (!writable || !mDatabase.isReadOnly()) {
        // The database is already open for business.
        return mDatabase;
      }
    }

    if (mIsInitializing) {
      throw new IllegalStateException("getDatabase called recursively");
    }

    SQLiteDatabase db = mDatabase;
    try {
      mIsInitializing = true;

      if (db != null) {
        if (writable && db.isReadOnly()) {
          db.reopenReadWrite();
        }
      } else if (mName == null) {
        db = SQLiteDatabase.create(null);
      } else {
        try {
          if (DEBUG_STRICT_READONLY && !writable) {
            final String path = mContext.getDatabasePath(mName).getPath();
            db =
                SQLiteDatabase.openDatabase(
                    path, mFactory, SQLiteDatabase.OPEN_READONLY, mErrorHandler);
          } else {
            db =
                mContext.openOrCreateDatabase(
                    mName,
                    mEnableWriteAheadLogging ? Context.MODE_ENABLE_WRITE_AHEAD_LOGGING : 0,
                    mFactory,
                    mErrorHandler);
          }
        } catch (SQLiteException ex) {
          if (writable) {
            throw ex;
          }
          Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", ex);
          final String path = mContext.getDatabasePath(mName).getPath();
          db =
              SQLiteDatabase.openDatabase(
                  path, mFactory, SQLiteDatabase.OPEN_READONLY, mErrorHandler);
        }
      }

      onConfigure(db);

      final int version = db.getVersion();
      if (version != mNewVersion) {
        if (db.isReadOnly()) {
          throw new SQLiteException(
              "Can't upgrade read-only database from version "
                  + db.getVersion()
                  + " to "
                  + mNewVersion
                  + ": "
                  + mName);
        }

        db.beginTransaction();
        try {
          if (version == 0) {
            onCreate(db);
          } else {
            if (version > mNewVersion) {
              onDowngrade(db, version, mNewVersion);
            } else {
              onUpgrade(db, version, mNewVersion);
            }
          }
          db.setVersion(mNewVersion);
          db.setTransactionSuccessful();
        } finally {
          db.endTransaction();
        }
      }

      onOpen(db);

      if (db.isReadOnly()) {
        Log.w(TAG, "Opened " + mName + " in read-only mode");
      }

      mDatabase = db;
      return db;
    } finally {
      mIsInitializing = false;
      if (db != null && db != mDatabase) {
        db.close();
      }
    }
  }