예제 #1
0
  /**
   * Inserts values into a table that has an unique id as identifier.
   *
   * @param table The affected table.
   * @param values The values to be inserted/ updated.
   * @param mId The identifier of the affected row.
   * @return The number of rows affected on update, the rowId on insert, -1 on error.
   */
  public int doInsertOrUpdate(String table, ContentValues values, Where where) {
    int result;

    open();
    Cursor oldVersion = get(table, where, null);

    if (oldVersion.moveToNext() && values.size() != 0) {
      String whereClause = null;
      if (where != null) {
        whereClause = where.toString().replace(" WHERE ", "");
      }

      result = mDb.update(table, values, whereClause, null);
    } else {
      String nullColumnHack = null;

      if (values.size() == 0) {
        // if no fields are defined on a model instance the nullColumnHack
        // needs to be utilized in order to insert an empty row.
        nullColumnHack = Model.PK;
      }

      result = (int) mDb.insertOrThrow(table, nullColumnHack, values);
    }

    oldVersion.close();
    close();
    return result;
  }
예제 #2
0
  /**
   * Saves a HashMap of metadata into the database. Will iterate through columns in the Database and
   * only save rows with matching keys in the HashMap. Must not be called from UI or Gecko threads.
   */
  public static void save(
      final ContentResolver cr, final String url, final Map<String, Object> data) {
    ThreadUtils.assertNotOnUiThread();
    ThreadUtils.assertNotOnGeckoThread();

    try {
      ContentValues values = new ContentValues();

      Set<String> model = getModel();
      for (String key : model) {
        if (data.containsKey(key)) {
          values.put(key, (String) data.get(key));
        }
      }

      if (values.size() == 0) {
        return;
      }

      Uri uri =
          URLMetadataTable.CONTENT_URI
              .buildUpon()
              .appendQueryParameter(BrowserContract.PARAM_INSERT_IF_NEEDED, "true")
              .build();
      cr.update(
          uri,
          values,
          URLMetadataTable.URL_COLUMN + "=?",
          new String[] {(String) data.get(URLMetadataTable.URL_COLUMN)});
    } catch (Exception ex) {
      Log.e(LOGTAG, "error saving", ex);
    }
  }
예제 #3
0
  /** Update objects (one or several records) in the database */
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    SQLiteDatabase db = MyContextHolder.get().getDatabase().getWritableDatabase();
    int count = 0;
    ParsedUri uriParser = ParsedUri.fromUri(uri);
    long accountUserId = 0;
    switch (uriParser.matched()) {
      case MSG:
        count = db.update(Msg.TABLE_NAME, values, selection, selectionArgs);
        break;

      case MSG_ITEM:
        accountUserId = uriParser.getAccountUserId();
        long rowId = uriParser.getMessageId();
        MsgOfUserValues msgOfUserValues = MsgOfUserValues.valueOf(accountUserId, values);
        msgOfUserValues.setMsgId(rowId);
        if (values.size() > 0) {
          count =
              db.update(
                  Msg.TABLE_NAME,
                  values,
                  BaseColumns._ID
                      + "="
                      + rowId
                      + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),
                  selectionArgs);
        }
        count += msgOfUserValues.update(db);
        break;

      case USER:
        count = db.update(User.TABLE_NAME, values, selection, selectionArgs);
        break;

      case USER_ITEM:
        accountUserId = uriParser.getAccountUserId();
        long selectedUserId = uriParser.getUserId();
        FollowingUserValues followingUserValues =
            FollowingUserValues.valueOf(accountUserId, selectedUserId, values);
        count =
            db.update(
                User.TABLE_NAME,
                values,
                BaseColumns._ID
                    + "="
                    + selectedUserId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),
                selectionArgs);
        followingUserValues.update(db);
        optionallyLoadAvatar(selectedUserId, values);
        break;

      default:
        throw new IllegalArgumentException(uriParser.toString());
    }

    return count;
  }
예제 #4
0
  /**
   * Save the given object to the database. Creates a new object if model id property has not been
   * set
   *
   * @return true on success.
   */
  public boolean persist(TYPE item) {
    if (item.getId() == AbstractModel.NO_ID) {
      return createNew(item);
    } else {
      ContentValues values = item.getSetValues();

      if (values.size() == 0) // nothing changed
      return true;

      return saveExisting(item);
    }
  }
예제 #5
0
파일: TaskDao.java 프로젝트: atexit/astrid
 @Override
 public boolean saveExisting(Task item) {
   ContentValues values = item.getSetValues();
   if (values == null || values.size() == 0) return false;
   if (!TaskApiDao.insignificantChange(values)) {
     item.setValue(Task.DETAILS, null);
     if (!values.containsKey(Task.MODIFICATION_DATE.name))
       item.setValue(Task.MODIFICATION_DATE, DateUtilities.now());
   }
   boolean result = super.saveExisting(item);
   if (result) afterSave(item, values);
   return result;
 }
예제 #6
0
 /**
  * Saves the given item. Will not create a new item!
  *
  * @param database
  * @param table table name
  * @param item item model
  * @return returns true on success.
  */
 public boolean saveExisting(TYPE item) {
   ContentValues values = item.getSetValues();
   if (values == null || values.size() == 0) // nothing changed
   return true;
   boolean result =
       database.update(
               table.name, values, AbstractModel.ID_PROPERTY.eq(item.getId()).toString(), null)
           > 0;
   if (result) {
     onModelUpdated(item);
     item.markSaved();
   }
   return result;
 }
  private void updateInDB() {

    if (_mWhereClause != null) {
      ContentValues lValues = new ContentValues();
      String[] lArgs = new String[_mWhereClauseColumns.length];
      int lSize = _mListOfColumns.size();

      for (int i = 0; i < lSize; i++) {

        String lColumnName = _mListOfColumns.get(i).getName();
        TCell lCell = cellByName(lColumnName);
        String lColumnValue = lCell.asString();
        DBAccessMode lAccessMode = lCell.getDBAccessMode();

        if (lAccessMode == DBAccessMode.UPDATE) lValues.put(lColumnName, lColumnValue);
      }

      for (int i = 0; i < _mWhereClauseColumns.length; i++) {

        if (indexOfColumn(_mWhereClauseColumns[i]) == -1) {
          PuUtils.showMessage(
              _mContext,
              "Erreur Column",
              "Column "
                  + _mWhereClauseColumns[i]
                  + " de clause Where  "
                  + "n'est pas une column de client data table :"
                  + _mCDTName);
          return;
        } else if (lValues.containsKey(_mWhereClauseColumns[i])) {
          PuUtils.showMessage(
              _mContext,
              "Erreur Column",
              "impossible de definir la colonne "
                  + _mWhereClauseColumns[i]
                  + " de clause Where comme colonne à modifier dans le CDT:"
                  + _mCDTName);
          return;
        }
        TCell lCell = cellByName(_mWhereClauseColumns[i]);
        lArgs[i] = lCell.asString();
      }
      if (lValues.size() != 0)
        _mSqliteDataBase.update(_mTableName, lValues, _mWhereClause.toString(), lArgs);
    } else PuUtils.showMessage(_mContext, "Erreur Update", "Clause where non definit");
  }
 private MatrixCursor getMatrixCursor(String id, String[] projection, ContentValues values) {
   Cursor c = get(id);
   if (c != null) {
     // Make a new MatrixCursor with the requested columns
     MatrixCursor mc = new MatrixCursorWithCachedColumns(projection, 1);
     if (c.getCount() == 0) {
       return mc;
     }
     Object[] row = new Object[projection.length];
     if (values != null) {
       // Make a copy; we don't want to change the original
       values = new ContentValues(values);
     }
     int i = 0;
     for (String column : projection) {
       int columnIndex = c.getColumnIndex(column);
       if (columnIndex < 0) {
         mStats.mProjectionMissCount++;
         return null;
       } else {
         String value;
         if (values != null && values.containsKey(column)) {
           Object val = values.get(column);
           if (val instanceof Boolean) {
             value = (val == Boolean.TRUE) ? "1" : "0";
           } else {
             value = values.getAsString(column);
           }
           values.remove(column);
         } else {
           value = c.getString(columnIndex);
         }
         row[i++] = value;
       }
     }
     if (values != null && values.size() != 0) {
       return null;
     }
     mc.addRow(row);
     mStats.mHitCount++;
     return mc;
   }
   mStats.mMissCount++;
   return null;
 }
  public String printContentValues(ContentValues vals) {
    String str_message = new String();
    Set<Map.Entry<String, Object>> s = vals.valueSet();
    Iterator itr = s.iterator();

    Log.d("DatabaseSync", "ContentValue Length :: " + vals.size());

    while (itr.hasNext()) {
      Map.Entry me = (Map.Entry) itr.next();
      String key = me.getKey().toString();
      Object value = me.getValue();
      if (key != ApparelDB.ApparelTable.COLUMN_NAME_APPAREL_IMG
          || (key != ApparelDB.ApparelTable.COLUMN_NAME_ALL_PIECES_IMG)) {
        str_message += key + " : " + (String) (value == null ? null : value.toString()) + "\r\n";
      }
    }
    return str_message;
  }
  private void insertInDB() {

    ContentValues lValues = new ContentValues();

    int lSize = _mListOfColumns.size();

    for (int i = 0; i < lSize; i++) {

      String lColumnName = _mListOfColumns.get(i).getName();
      TCell lCell = cellByName(lColumnName);
      String lColumnValue = lCell.asString();
      DBAccessMode lAccessMode = lCell.getDBAccessMode();

      if (lAccessMode == DBAccessMode.INSERT) lValues.put(lColumnName, lColumnValue);
    }
    if (lValues.size() == 0) {
      PuUtils.showMessage(_mContext, "Erreur insertion", "Acune valeur définie pour inserer");
      return;
    }
    _mSqliteDataBase.insertOrThrow(_mTableName, null, lValues);
  }
예제 #11
0
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    if (values.size() == 0) return null;
    switch (_uriMatcher.match(uri)) {
      case SUBSCRIPTIONS:
        break;
      default:
        throw new IllegalArgumentException("Unknown URI");
    }

    if (Helper.isGPodderInstalled(getContext())) {
      ContentValues gpodderValues = new ContentValues();
      gpodderValues.put("url", values.getAsString(COLUMN_URL));
      getContext().getContentResolver().insert(Constants.GPODDER_URI, gpodderValues);
    }

    SQLiteDatabase db = _dbAdapter.getWritableDatabase();
    long id = db.insert("subscriptions", null, values);
    getContext().getContentResolver().notifyChange(URI, null);
    return ContentUris.withAppendedId(URI, id);
  }
  public static int addTransaction(Context context, ClassExpenseTransaction transaction) {

    if (transaction.id.equals("")) return -1;

    final String[] selectionArgs = new String[] {transaction.id};

    ContentValues updateValues = new ContentValues(0);

    if (transaction.id != null) updateValues.put(KEY_ID, transaction.id);

    if (transaction.id_parent != null) updateValues.put(KEY_ID_PARENT, transaction.id_parent);

    if (transaction.note != null) updateValues.put(KEY_NAME, transaction.name);

    updateValues.put(KEY_AMOUNT, transaction.amount);

    if (transaction.from_income != null) updateValues.put(KEY_FROM_INCOME, transaction.from_income);
    //
    if (transaction.date != null) updateValues.put(KEY_DATE, transaction.date);

    if (transaction.note != null) updateValues.put(KEY_NOTE, transaction.note);

    if (updateValues.size() <= 0) return 0;

    int updateRowCount =
        ProviderSuper.update(context, CONTENT_URI, updateValues, SELECTION, selectionArgs);

    if (updateRowCount <= 0) {

      ContentValues addValues = getContentValues(transaction);

      ProviderSuper.insert(context, CONTENT_URI, addValues);
    }

    return updateRowCount;
  }
예제 #13
0
  /** Updates a row in the database */
  @Override
  public int update(
      final Uri uri, final ContentValues values, final String where, final String[] whereArgs) {

    Helpers.validateSelection(where, sAppReadableColumnsSet);

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    int count;
    boolean startService = false;

    if (values.containsKey(Downloads.COLUMN_DELETED)) {
      if (values.getAsInteger(Downloads.COLUMN_DELETED) == 1) {
        // some rows are to be 'deleted'. need to start DownloadService.
        startService = true;
      }
    }

    ContentValues filteredValues;
    if (Binder.getCallingPid() != Process.myPid()) {
      filteredValues = new ContentValues();
      copyString(Downloads.COLUMN_APP_DATA, values, filteredValues);
      copyInteger(Downloads.COLUMN_VISIBILITY, values, filteredValues);
      Integer i = values.getAsInteger(Downloads.COLUMN_CONTROL);
      if (i != null) {
        filteredValues.put(Downloads.COLUMN_CONTROL, i);
        startService = true;
      }

      copyInteger(Downloads.COLUMN_CONTROL, values, filteredValues);
      copyString(Downloads.COLUMN_TITLE, values, filteredValues);
      copyString(Downloads.COLUMN_DESCRIPTION, values, filteredValues);
      copyInteger(Downloads.COLUMN_DELETED, values, filteredValues);
    } else {
      filteredValues = values;
      String filename = values.getAsString(Downloads._DATA);
      if (filename != null) {
        Cursor c = query(uri, new String[] {Downloads.COLUMN_TITLE}, null, null, null);
        if (!c.moveToFirst() || c.getString(0).length() == 0) {
          values.put(Downloads.COLUMN_TITLE, new File(filename).getName());
        }
        c.close();
      }

      Integer status = values.getAsInteger(Downloads.COLUMN_STATUS);
      boolean isRestart = status != null && status == Downloads.STATUS_PENDING;
      boolean isUserBypassingSizeLimit =
          values.containsKey(Downloads.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT);
      if (isRestart || isUserBypassingSizeLimit) {
        startService = true;
      }
    }

    int match = sURIMatcher.match(uri);
    switch (match) {
      case MY_DOWNLOADS:
      case MY_DOWNLOADS_ID:
      case ALL_DOWNLOADS:
      case ALL_DOWNLOADS_ID:
        SqlSelection selection = getWhereClause(uri, where, whereArgs, match);
        if (filteredValues.size() > 0) {
          count =
              db.update(
                  DB_TABLE, filteredValues, selection.getSelection(), selection.getParameters());
        } else {
          count = 0;
        }
        break;

      default:
        Log.d(Constants.TAG, "updating unknown/invalid URI: " + uri);
        throw new UnsupportedOperationException("Cannot update URI: " + uri);
    }

    notifyContentChanged(uri, match);
    if (startService) {
      Context context = getContext();
      context.startService(new Intent(context, DownloadService.class));
    }
    return count;
  }
예제 #14
0
  @Override
  public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    SQLiteDatabase db = _dbAdapter.getWritableDatabase();
    if (db == null) return 0;

    long podcastId;
    SharedPreferences prefs = getContext().getSharedPreferences("internals", Context.MODE_PRIVATE);
    Long activePodcastId = prefs.getLong(PREF_ACTIVE, -1);

    int uriMatch = uriMatcher.match(uri);
    if (uriMatch == PODCASTS) {
      int count = db.update("podcasts", values, where, whereArgs);
      // only main uri is notified
      getContext().getContentResolver().notifyChange(URI, null);
      return count;
    }

    // tell gpodder the new position
    if (values.containsKey(COLUMN_LAST_POSITION)) {
      values.put(COLUMN_NEEDS_GPODDER_UPDATE, Constants.GPODDER_UPDATE_POSITION);
      values.put(COLUMN_GPODDER_UPDATE_TIMESTAMP, new Date().getTime());
    }

    // process the player update separately
    if (uriMatch == PODCAST_PLAYER_UPDATE) {
      if (activePodcastId == -1) return 0;
      Cursor c =
          db.query(
              "podcasts",
              new String[] {"lastPosition", "needsGpodderUpdate"},
              "_id = ?",
              new String[] {String.valueOf(activePodcastId)},
              null,
              null,
              null);
      c.moveToFirst();
      int oldPosition = c.getInt(0);
      c.close();
      int newPosition = values.getAsInteger(COLUMN_LAST_POSITION);
      // reject changes if it's not a normal update
      if (newPosition < oldPosition || newPosition - oldPosition > 5000) return 0;

      db.update("podcasts", values, "_id = ?", new String[] {String.valueOf(activePodcastId)});
      getContext().getContentResolver().notifyChange(ACTIVE_PODCAST_URI, null);
      getContext()
          .getContentResolver()
          .notifyChange(ContentUris.withAppendedId(URI, activePodcastId), null);
      ActivePodcastReceiver.notifyExternal(getContext());
      return 1;
    }

    switch (uriMatch) {
      case PODCAST_ID:
        podcastId = ContentUris.parseId(uri);
        break;
      case PODCAST_ACTIVE:
        if (values.containsKey(COLUMN_ID)) {
          activePodcastId = values.getAsLong(COLUMN_ID);
          Editor editor = prefs.edit();
          if (activePodcastId != null) editor.putLong(PREF_ACTIVE, values.getAsLong(COLUMN_ID));
          else editor.remove(PREF_ACTIVE);
          editor.commit();

          // if we're clearing the active podcast or updating just the ID, don't go to the DB
          if (activePodcastId == null || values.size() == 1) {
            getContext().getContentResolver().notifyChange(ACTIVE_PODCAST_URI, null);
            return 0;
          }
        }

        // if we don't have an active podcast, don't update it
        if (activePodcastId == -1) return 0;

        podcastId = activePodcastId;
        break;
      default:
        throw new IllegalArgumentException("Unknown URI");
    }

    String extraWhere = COLUMN_ID + " = " + podcastId;
    if (where != null) where = extraWhere + " AND " + where;
    else where = extraWhere;

    // don't try to update subscription values
    values.remove(COLUMN_SUBSCRIPTION_TITLE);
    values.remove(COLUMN_SUBSCRIPTION_THUMBNAIL);
    values.remove(COLUMN_SUBSCRIPTION_URL);

    // update queuePosition separately
    if (values.containsKey(COLUMN_QUEUE_POSITION)) {
      // get the new position
      Integer newPosition = values.getAsInteger(COLUMN_QUEUE_POSITION);
      values.remove(COLUMN_QUEUE_POSITION);

      // no way to get changed record count until
      // SQLiteStatement.executeUpdateDelete in API level 11
      updateQueuePosition(podcastId, newPosition);

      // if this was the active podcast and it's no longer in the queue or it was moved to the back
      // don't restart on this podcast
      if (activePodcastId == podcastId
          && (newPosition == null || newPosition == Integer.MAX_VALUE)) {
        prefs.edit().remove(PREF_ACTIVE).commit();
        activePodcastId = podcastId; // make sure the active podcast notification is sent
      }

      // if there is no active podcast, the active podcast may have changed
      if (activePodcastId == -1) activePodcastId = podcastId;
    }

    int count = 0;
    if (values.size() > 0) count += db.update("podcasts", values, where, whereArgs);
    getContext()
        .getContentResolver()
        .notifyChange(ContentUris.withAppendedId(URI, podcastId), null);
    if (values.containsKey(COLUMN_FILE_SIZE))
      getContext()
          .getContentResolver()
          .notifyChange(Uri.withAppendedPath(URI, "to_download"), null);
    if (podcastId == activePodcastId) {
      getContext().getContentResolver().notifyChange(ACTIVE_PODCAST_URI, null);
      ActivePodcastReceiver.notifyExternal(getContext());
    }
    // if the current podcast has updated the position but it's not from the player, tell the player
    // to update
    if (podcastId == activePodcastId
        && uriMatch != PODCAST_PLAYER_UPDATE
        && values.containsKey(COLUMN_LAST_POSITION))
      getContext().getContentResolver().notifyChange(PLAYER_UPDATE_URI, null);

    return count;
  }
 @Override
 public int size() {
   return contentValues.size();
 }
예제 #16
0
 /**
  * Updates multiple rows of the database based on model set values
  *
  * @param item item model
  * @param criterion
  * @return returns true on success.
  */
 public int updateMultiple(ContentValues values, Criterion criterion) {
   if (values.size() == 0) // nothing changed
   return 0;
   return database.update(table.name, values, criterion.toString(), null);
 }