Пример #1
0
  /** Reads the given property. Make sure this model has this property! */
  public synchronized <TYPE> TYPE getValue(Property<TYPE> property) {
    Object value;
    if (setValues != null && setValues.containsKey(property.getColumnName())) {
      value = setValues.get(property.getColumnName());
    } else if (values != null && values.containsKey(property.getColumnName())) {
      value = values.get(property.getColumnName());
    } else if (getDefaultValues().containsKey(property.getColumnName())) {
      value = getDefaultValues().get(property.getColumnName());
    } else {
      throw new UnsupportedOperationException(
          "Model Error: Did not read property " + property.name); // $NON-NLS-1$
    }

    // resolve properties that were retrieved with a different type than accessed
    try {
      if (value instanceof String && property instanceof LongProperty) {
        return (TYPE) Long.valueOf((String) value);
      } else if (value instanceof String && property instanceof IntegerProperty) {
        return (TYPE) Integer.valueOf((String) value);
      } else if (value instanceof Integer && property instanceof LongProperty) {
        return (TYPE) Long.valueOf(((Number) value).longValue());
      }
      return (TYPE) value;
    } catch (NumberFormatException e) {
      return (TYPE) getDefaultValues().get(property.name);
    }
  }
Пример #2
0
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    if (sUriMatcher.match(uri) != INCOMING_CONTACT_COLLECTION_URI_INDICATOR) {
      throw new IllegalArgumentException("Unknow URI " + uri);
    }

    Log.d(TAG, "Enter insert");

    if (!values.containsKey(ContactTableMetaData.CONTACT_ACCOUNT)) {
      throw new IllegalArgumentException("Failed to insert row, account is needed " + uri);
    }

    if (!values.containsKey(ContactTableMetaData.CONTACT_NICKNAME)) {
      values.put(
          ContactTableMetaData.CONTACT_NICKNAME,
          (String) values.get(ContactTableMetaData.CONTACT_ACCOUNT));
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowId =
        db.insert(ContactTableMetaData.TABLE_NAME, ContactTableMetaData.CONTACT_ACCOUNT, values);
    if (rowId > 0) {
      Uri insertContactUri = ContentUris.withAppendedId(ContactTableMetaData.CONTENT_URI, rowId);
      getContext().getContentResolver().notifyChange(insertContactUri, null);

      Log.d(TAG, "insert uri=% " + insertContactUri.toString());
      return insertContactUri;
    }

    throw new SQLiteException("Failed to insert row int " + uri);
  }
  @Override
  public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    SQLiteDatabase db = getDbHelper().getWritableDatabase();

    Long now = Long.valueOf(System.currentTimeMillis());

    // Make sure that the fields are all set
    if (values.containsKey(InstanceColumns.LAST_STATUS_CHANGE_DATE) == false) {
      values.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, now);
    }

    int count;
    String status = null;
    switch (sUriMatcher.match(uri)) {
      case INSTANCES:
        if (values.containsKey(InstanceColumns.STATUS)) {
          status = values.getAsString(InstanceColumns.STATUS);

          if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
            Date today = new Date();
            String text = getDisplaySubtext(status, today);
            values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
          }
        }

        count = db.update(INSTANCES_TABLE_NAME, values, where, whereArgs);
        break;

      case INSTANCE_ID:
        String instanceId = uri.getPathSegments().get(1);

        if (values.containsKey(InstanceColumns.STATUS)) {
          status = values.getAsString(InstanceColumns.STATUS);

          if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
            Date today = new Date();
            String text = getDisplaySubtext(status, today);
            values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
          }
        }

        count =
            db.update(
                INSTANCES_TABLE_NAME,
                values,
                InstanceColumns._ID
                    + "="
                    + instanceId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
                whereArgs);
        break;

      default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return count;
  }
Пример #4
0
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    SQLiteDatabase db = _dbAdapter.getWritableDatabase();

    if (!(uriMatcher.match(uri) == PODCASTS))
      throw new IllegalArgumentException("Illegal URI for insert");
    if (values.get(COLUMN_MEDIA_URL) == null)
      throw new IllegalArgumentException("mediaUrl is required field for podcast");

    Cursor mediaUrlCursor =
        db.rawQuery(
            "SELECT _id FROM podcasts WHERE mediaUrl = ?",
            new String[] {values.getAsString(COLUMN_MEDIA_URL)});
    Long podcastId = null;
    if (mediaUrlCursor.moveToNext()) podcastId = mediaUrlCursor.getLong(0);
    mediaUrlCursor.close();

    if (podcastId != null) {
      if (values.containsKey(COLUMN_MEDIA_URL) && values.containsKey(COLUMN_FILE_SIZE)) {
        String file =
            PodcastCursor.getStoragePath(getContext())
                + String.valueOf(podcastId)
                + "."
                + PodcastCursor.getExtension(values.getAsString(COLUMN_MEDIA_URL));
        // possible bug: file size shrinks for some reason -- don't use new one
        if (new File(file).length() > values.getAsInteger(COLUMN_FILE_SIZE))
          values.remove(COLUMN_FILE_SIZE);
      }
      db.update("podcasts", values, COLUMN_ID + " = ?", new String[] {String.valueOf(podcastId)});
    } else {
      podcastId = db.insert("podcasts", null, values);

      // find out if we should download new podcasts
      Cursor queueNewCursor =
          db.query(
              "subscriptions",
              new String[] {SubscriptionProvider.COLUMN_QUEUE_NEW},
              "_id = ?",
              new String[] {String.valueOf(values.getAsLong(COLUMN_SUBSCRIPTION_ID))},
              null,
              null,
              null);
      queueNewCursor.moveToFirst();
      boolean queueNew = queueNewCursor.getInt(0) != 0;
      queueNewCursor.close();

      // if the new podcast is less than 5 days old , and add it to the queue
      if (queueNew && values.containsKey(COLUMN_PUB_DATE)) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -5);
        if (new Date(values.getAsLong(COLUMN_PUB_DATE) * 1000L).after(c.getTime())) {
          updateQueuePosition(podcastId, Integer.MAX_VALUE);
        }
      }
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return PodcastProvider.getContentUri(podcastId);
  }
 @Test
 public void testMessageToContentValuesWithCalllogFromUnknownPerson() throws Exception {
   PersonRecord record = new PersonRecord(-1, null, null, null);
   when(personLookup.lookupPerson("+12121")).thenReturn(record);
   final ContentValues values = messageConverter.messageToContentValues(createCallLogMessage());
   assertThat(values.containsKey(CallLog.Calls.CACHED_NAME)).isFalse();
   assertThat(values.containsKey(CallLog.Calls.CACHED_NUMBER_TYPE)).isFalse();
 }
Пример #6
0
 /** Clear the key for the given property */
 public synchronized void clearValue(Property<?> property) {
   if (setValues != null && setValues.containsKey(property.getColumnName())) {
     setValues.remove(property.getColumnName());
   }
   if (values != null && values.containsKey(property.getColumnName())) {
     values.remove(property.getColumnName());
   }
 }
Пример #7
0
 protected long getIdHelper(LongProperty id) {
   if (setValues != null && setValues.containsKey(id.name)) {
     return setValues.getAsLong(id.name);
   } else if (values != null && values.containsKey(id.name)) {
     return values.getAsLong(id.name);
   } else {
     return NO_ID;
   }
 }
Пример #8
0
 /**
  * @return true if setValues or values contains this property, and the value stored is not null
  */
 public boolean containsNonNullValue(Property<?> property) {
   if (setValues != null && setValues.containsKey(property.getColumnName())) {
     return setValues.get(property.getColumnName()) != null;
   }
   if (values != null && values.containsKey(property.getColumnName())) {
     return values.get(property.getColumnName()) != null;
   }
   return false;
 }
Пример #9
0
 /** Check defaults */
 public void checkDefaults() {
   Preferences.setPreferenceDefaults();
   ContentValues defaults = new Task().getDefaultValues();
   assertTrue(defaults.containsKey(Task.TITLE.name));
   assertTrue(defaults.containsKey(Task.DUE_DATE.name));
   assertTrue(defaults.containsKey(Task.HIDE_UNTIL.name));
   assertTrue(defaults.containsKey(Task.COMPLETION_DATE.name));
   assertTrue(defaults.containsKey(Task.IMPORTANCE.name));
 }
Пример #10
0
  @Override
  public CallerInfo findSelfInfo(Context ctxt) {

    CallerInfo callerInfo = new CallerInfo();

    String[] projection =
        new String[] {Profile._ID, Profile.DISPLAY_NAME, Profile.PHOTO_ID, Profile.PHOTO_URI};
    Cursor cursor =
        ctxt.getContentResolver()
            .query(ContactsContract.Profile.CONTENT_URI, projection, null, null, null);
    if (cursor != null) {
      try {
        if (cursor.getCount() > 0) {
          cursor.moveToFirst();

          ContentValues cv = new ContentValues();
          DatabaseUtils.cursorRowToContentValues(cursor, cv);
          callerInfo.contactExists = true;
          if (cv.containsKey(Profile.DISPLAY_NAME)) {
            callerInfo.name = cv.getAsString(Profile.DISPLAY_NAME);
          }

          if (cv.containsKey(Profile._ID)) {
            callerInfo.personId = cv.getAsLong(Profile._ID);
            callerInfo.contactContentUri =
                ContentUris.withAppendedId(Contacts.CONTENT_URI, callerInfo.personId);
          }

          if (cv.containsKey(Profile.PHOTO_ID)) {
            Long photoId = cv.getAsLong(Profile.PHOTO_ID);
            if (photoId != null) {
              callerInfo.photoId = photoId;
            }
          }

          if (cv.containsKey(Profile.PHOTO_URI)) {
            String photoUri = cv.getAsString(Profile.PHOTO_URI);
            if (!TextUtils.isEmpty(photoUri)) {
              callerInfo.photoUri = Uri.parse(photoUri);
            }
          }

          if (callerInfo.name != null && callerInfo.name.length() == 0) {
            callerInfo.name = null;
          }
        }
      } catch (Exception e) {
        Log.e(THIS_FILE, "Exception while retrieving cursor infos", e);
      } finally {
        cursor.close();
      }
    }

    return callerInfo;
  }
Пример #11
0
  public void testSerialization() throws Exception {
    testTime();
    subject.setUniqueID(Integer.MAX_VALUE);
    ContentValues serialized = subject.toStorage();

    assertTrue(serialized.containsKey(DBAssistant.HIKE_START));
    assertTrue(serialized.containsKey(DBAssistant.HIKE_END));

    assertEquals(serialized.get(DBAssistant.HIKE_START), startTime);
    assertEquals(serialized.get(DBAssistant.HIKE_END), endTime);
  }
Пример #12
0
 @Override
 protected boolean shouldRecordOutstanding(TagMetadata item) {
   ContentValues cv = item.getSetValues();
   return super.shouldRecordOutstanding(item)
       && cv != null
       && ((cv.containsKey(TagMetadata.KEY.name)
               && TagMemberMetadata.KEY.equals(item.getValue(TagMetadata.KEY)))
           || (cv.containsKey(TagMetadata.DELETION_DATE.name)
               && item.getValue(TagMetadata.DELETION_DATE) > 0))
       && RemoteModelDao.getOutstandingEntryFlag(
           RemoteModelDao.OUTSTANDING_ENTRY_FLAG_RECORD_OUTSTANDING);
 }
  @Override
  public Uri insert(Uri uri, ContentValues initialValues) {
    // Validate the requested uri
    if (sUriMatcher.match(uri) != INSTANCES) {
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

    ContentValues values;
    if (initialValues != null) {
      values = new ContentValues(initialValues);
    } else {
      values = new ContentValues();
    }

    Long now = Long.valueOf(System.currentTimeMillis());

    // Make sure that the fields are all set
    if (values.containsKey(InstanceColumns.LAST_STATUS_CHANGE_DATE) == false) {
      values.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, now);
    }

    if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
      Date today = new Date();
      String text = getDisplaySubtext(InstanceProviderAPI.STATUS_INCOMPLETE, today);
      values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
    }

    if (values.containsKey(InstanceColumns.STATUS) == false) {
      values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
    }

    SQLiteDatabase db = getDbHelper().getWritableDatabase();
    long rowId = db.insert(INSTANCES_TABLE_NAME, null, values);
    if (rowId > 0) {
      Uri instanceUri = ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, rowId);
      getContext().getContentResolver().notifyChange(instanceUri, null);
      Collect.getInstance()
          .getActivityLogger()
          .logActionParam(
              this,
              "insert",
              instanceUri.toString(),
              values.getAsString(InstanceColumns.INSTANCE_FILE_PATH));
      return instanceUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
  }
Пример #14
0
  @Override
  public Uri insert(Uri uri, ContentValues initialValues) {
    // Validate the requested uri
    if (sUriMatcher.match(uri) != RECIPES) {
      throw new IllegalArgumentException("Unknown URI on insert attempt: " + uri);
    }

    ContentValues values;
    if (initialValues != null) {
      values = new ContentValues(initialValues);
    } else {
      values = new ContentValues();
    }

    Long now = Long.valueOf(System.currentTimeMillis());

    // Make sure that the fields are all set
    if (values.containsKey(Cookbook.Recipes.CREATED_DATE) == false) {
      values.put(Cookbook.Recipes.CREATED_DATE, now);
    }

    if (values.containsKey(Cookbook.Recipes.MODIFIED_DATE) == false) {
      values.put(Cookbook.Recipes.MODIFIED_DATE, now);
    }

    if (values.containsKey(Cookbook.Recipes.TITLE) == false) {
      Resources r = Resources.getSystem();
      values.put(Cookbook.Recipes.TITLE, r.getString(android.R.string.untitled));
    }

    if (values.containsKey(Cookbook.Recipes.RECIPE) == false) {
      values.put(Cookbook.Recipes.RECIPE, "");
    }

    if (values.containsKey(Cookbook.Recipes.SOURCE_URI) == false) {
      values.put(Cookbook.Recipes.SOURCE_URI, "");
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowId = db.insert(RECIPES_TABLE_NAME, Recipes.RECIPE, values);
    if (rowId > 0) {
      Uri recipeUri = ContentUris.withAppendedId(Cookbook.Recipes.CONTENT_URI, rowId);
      getContext().getContentResolver().notifyChange(recipeUri, null);
      return recipeUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
  }
Пример #15
0
  @SuppressLint("SimpleDateFormat")
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    // TODO Auto-generated method stub
    // 新增,故uri只能为collection
    if (sUriMatch.match(uri) != HISTORY_COLLECTION_URI_INDICATOR) {
      throw new IllegalArgumentException("URI =" + uri);
    }
    // 允许插入空行
    ContentValues cv;
    if (values == null) {
      cv = new ContentValues();
    } else {
      cv = new ContentValues(values);
    }
    //
    if (cv.containsKey(ChatHistoryTable.CHAT_TIME)) {
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd-HH:mm:ss");
      String now = sdf.format(new Date(System.currentTimeMillis()));
      cv.put(ChatHistoryTable.CHAT_TIME, now);
    }

    mDb = mOpenHelper.getWritableDatabase();
    long rowId = mDb.insert(ChatHistoryTable.TABLE_NAME, null, cv);
    if (rowId > 0) {
      Uri insertUri = ContentUris.withAppendedId(ChatHistoryTable.CONTENT_URI, rowId);
      mContentResolver.notifyChange(insertUri, null);
      return insertUri;
    }
    throw new SQLiteException("Failed to insert!!!");
  }
  /** Update a direct message */
  @Override
  public synchronized int update(
      Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    if (dmUriMatcher.match(uri) != DM_ID)
      throw new IllegalArgumentException("Unsupported URI: " + uri);

    Log.d(TAG, "Update DM_ID");

    int nrRows =
        database.update(DBOpenHelper.TABLE_DMS, values, "_id=" + uri.getLastPathSegment(), null);
    if (nrRows >= 0) {
      getContext().getContentResolver().notifyChange(uri, null);
      getContext().getContentResolver().notifyChange(DirectMessages.CONTENT_URI, null);

      if (values.containsKey(DirectMessages.COL_FLAGS)
          && values.getAsInteger(DirectMessages.COL_FLAGS) != 0) {

        Intent i = new Intent(getContext(), TwitterSyncService.class);
        i.putExtra(
            TwitterSyncService.EXTRA_KEY_ACTION,
            TwitterSyncService.EXTRA_ACTION_SYNC_TRANSACTIONAL_MESSAGES);
        getContext().startService(i);
      }

      return nrRows;
    } else {
      throw new IllegalStateException("Could not update direct message " + values);
    }
  }
Пример #17
0
  /** Synchronize with server when data changes */
  public void pushUpdateOnSave(Update update, ContentValues values) {
    if (!values.containsKey(Update.MESSAGE.name)) return;

    ArrayList<Object> params = new ArrayList<Object>();
    params.add("message");
    params.add(update.getValue(Update.MESSAGE));

    if (update.getValue(Update.TAG) > 0) {
      TagData tagData = tagDataService.fetchById(update.getValue(Update.TAG), TagData.REMOTE_ID);
      if (tagData == null || tagData.getValue(TagData.REMOTE_ID) == 0) return;
      params.add("tag_id");
      params.add(tagData.getValue(TagData.REMOTE_ID));
    }

    if (update.getValue(Update.TASK) > 0) {
      params.add("task_id");
      params.add(update.getValue(Update.TASK));
    }
    if (!checkForToken()) return;

    try {
      params.add("token");
      params.add(token);
      JSONObject result =
          actFmInvoker.invoke("comment_add", params.toArray(new Object[params.size()]));
      update.setValue(Update.REMOTE_ID, result.optLong("id"));
      updateDao.saveExisting(update);
    } catch (IOException e) {
      handleException("task-save", e);
    }
  }
Пример #18
0
  @Override
  public Uri insert(Uri url, ContentValues initialValues) {
    if (URI_MATCHER.match(url) != CONTACTS) {
      throw new IllegalArgumentException("Cannot insert into URL: " + url);
    }

    ContentValues values =
        (initialValues != null) ? new ContentValues(initialValues) : new ContentValues();

    for (String colName : RosterConstants.getRequiredColumns()) {
      if (values.containsKey(colName) == false) {
        throw new IllegalArgumentException("Missing column: " + colName);
      }
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    long rowId = db.insert(TABLE_ROSTER, RosterConstants.USER_ID, values);

    if (rowId < 0) {
      throw new SQLException("Failed to insert row into " + url);
    }

    Uri noteUri = ContentUris.withAppendedId(CONTENT_URI, rowId);

    notifyChange();

    return noteUri;
  }
Пример #19
0
 private static final void copyStringWithDefault(
     String key, ContentValues from, ContentValues to, String defaultValue) {
   copyString(key, from, to);
   if (!to.containsKey(key)) {
     to.put(key, defaultValue);
   }
 }
 private void normalizeDate(ContentValues values) {
   // normalize the date value
   if (values.containsKey(WeatherEntry.COLUMN_DATE)) {
     long dateValue = values.getAsLong(WeatherEntry.COLUMN_DATE);
     values.put(WeatherEntry.COLUMN_DATE, WeatherContract.normalizeDate(dateValue));
   }
 }
Пример #21
0
  @Override
  protected void onPause() {
    super.onPause();

    if (mUri != null) {
      String bodyText = mBodyText.getText().toString();
      int length = bodyText.length();

      if ((mState == STATE_INSERT) && isFinishing() && (length == 0)) {
        // If inserting and finishing and no text then delete the note.
        setResult(RESULT_CANCELED);
        deleteNote();
      } else {
        ContentValues values = mOriginalNote.getContentValues();
        if (values.containsKey(Note._ID)) values.remove(Note._ID);

        if (mState == STATE_INSERT) {
          String[] lines = bodyText.split("[\n\\.]");
          String title = (lines.length > 0) ? lines[0] : getString(android.R.string.untitled);
          if (title.length() > 30) {
            int lastSpace = title.lastIndexOf(' ');
            if (lastSpace > 0) {
              title = title.substring(0, lastSpace);
            }
          }
          values.put(Note.TITLE, title);
        }
        values.put(Note.BODY, bodyText);
        values.put(Note.CURSOR, mBodyText.getSelectionStart());
        values.put(Note.SCROLL_Y, mBodyText.getScrollY());

        getContentResolver().update(mUri, values, null, null);
      }
    }
  }
Пример #22
0
  @Override
  public Uri insert(Uri uri, ContentValues initialValues) {
    if (!accept()) {
      return null;
    }

    // Validate the requested uri
    if (uriMatcher.match(uri) != SHARING_ALL) {
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

    ContentValues values;

    if (initialValues != null) {
      values = new ContentValues(initialValues);
    } else {
      values = new ContentValues();
    }

    // Make sure that the fields are all set
    if (values.containsKey(SharingColumns.FILE_ID) == false) {
      values.put(SharingColumns.FILE_ID, -1);
    }

    if (values.containsKey(SharingColumns.FILE_TYPE) == false) {
      values.put(SharingColumns.FILE_TYPE, -1);
    }

    if (values.containsKey(SharingColumns.SHARED) == false) {
      values.put(SharingColumns.SHARED, 0);
    }

    SQLiteDatabase db = databaseHelper.getWritableDatabase();

    long rowId = db.insert(SHARING_TABLE_NAME, "", values);

    if (rowId > 0) {
      Uri sharingUri = ContentUris.withAppendedId(Sharing.Media.CONTENT_URI, rowId);
      getContext().getContentResolver().notifyChange(sharingUri, null);

      return sharingUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
  }
Пример #23
0
  private void fill(ContentValues values) {
    if (!values.containsKey("data")) {
      values.put("data", "");
    }

    Calendar calendar = Calendar.getInstance();

    long time_in_millis = calendar.getTimeInMillis();
    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(time_in_millis));

    if (!values.containsKey("date")) {
      values.put("date", date);
    }

    if (!values.containsKey("time_in_millis")) {
      values.put("time_in_millis", time_in_millis);
    }
  }
Пример #24
0
  /**
   * Gets the id of current object if exists.
   *
   * @return Integer with id of current object. 0 if the object hasn't id.
   */
  public final int getId() {
    int id = 0;

    if (null != values && values.containsKey(JaiberdroidSql._ID)) {
      id = values.getAsInteger(JaiberdroidSql._ID);
    }

    return id;
  }
Пример #25
0
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    if (sUriMatcher.match(uri) == TYPE_RESTRICTION) {
      // Check access
      enforcePermission();

      // Get arguments
      String restrictionName = selection;
      int uid = values.getAsInteger(COL_UID);
      String methodName = values.getAsString(COL_METHOD);
      boolean allowed = !Boolean.parseBoolean(values.getAsString(COL_RESTRICTED));

      // Update
      updateRestriction(uid, restrictionName, methodName, allowed);

      return 1; // rows
    } else if (sUriMatcher.match(uri) == TYPE_USAGE) {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

      // Get arguments
      int uid = values.getAsInteger(COL_UID);
      String restrictionName = values.getAsString(PrivacyProvider.COL_RESTRICTION);
      String methodName = values.getAsString(COL_METHOD);
      boolean restricted = false;
      if (values.containsKey(PrivacyProvider.COL_RESTRICTED))
        restricted = values.getAsBoolean(PrivacyProvider.COL_RESTRICTED);
      long timeStamp = values.getAsLong(PrivacyProvider.COL_USED);
      Util.log(
          null,
          Log.INFO,
          String.format(
              "Update usage data %d/%s/%s=%b", uid, restrictionName, methodName, restricted));

      // Update usage data
      if (methodName != null) updateUsage(uid, restrictionName, methodName, restricted, timeStamp);

      return 1;
    } else if (sUriMatcher.match(uri) == TYPE_SETTING) {
      // Check access
      enforcePermission();

      // Get arguments
      String settingName = selection;

      // Update setting
      SharedPreferences prefs =
          getContext().getSharedPreferences(PREF_SETTINGS, Context.MODE_WORLD_READABLE);
      SharedPreferences.Editor editor = prefs.edit();
      editor.putString(getSettingPref(settingName), values.getAsString(COL_VALUE));
      editor.apply();
      setPrefFileReadable(PREF_SETTINGS);

      return 1;
    }

    throw new IllegalArgumentException(uri.toString());
  }
Пример #26
0
 /**
  * Creates an update {@link ContentProviderOperation} for the {@link App} in question.
  * <strong>Does not do any checks to see if the app already exists or not.</strong>
  */
 private ContentProviderOperation updateExistingApp(App app) {
   Uri uri = TempAppProvider.getAppUri(app);
   ContentValues values = app.toContentValues();
   for (final String toIgnore : APP_FIELDS_TO_IGNORE) {
     if (values.containsKey(toIgnore)) {
       values.remove(toIgnore);
     }
   }
   return ContentProviderOperation.newUpdate(uri).withValues(values).build();
 }
Пример #27
0
 /**
  * Merges set values with those coming from another source, keeping the existing value if one
  * already exists
  */
 public synchronized void mergeWithoutReplacement(ContentValues other) {
   if (setValues == null) {
     setValues = new ContentValues();
   }
   for (Entry<String, Object> item : other.valueSet()) {
     if (setValues.containsKey(item.getKey())) {
       continue;
     }
     AndroidUtilities.putInto(setValues, item.getKey(), item.getValue());
   }
 }
Пример #28
0
  /**
   * @param cv
   * @return
   */
  public static ContentValues prepareForUpdate(ContentValues cv, boolean forceSettUpdateDate) {

    cv.remove(BaseEntityColumns.COLUMN_CREATE_DATE);

    if ((true == forceSettUpdateDate) || (!cv.containsKey(BaseEntityColumns.COLUMN_MODIFY_DATE))) {

      cv.put(BaseEntityColumns.COLUMN_MODIFY_DATE, System.currentTimeMillis());
    }

    return cv;
  }
Пример #29
0
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

    if (LOGD) Log.d(TAG, "update");

    switch (URI_MATCHER.match(uri)) {
      case URI_TASKS:
        Task task = new Task();

        // map values
        if (values.containsKey(NAME)) task.setValue(Task.TITLE, values.getAsString(NAME));
        if (values.containsKey(PREFERRED_DUE_DATE))
          task.setValue(Task.DUE_DATE, values.getAsLong(PREFERRED_DUE_DATE));
        if (values.containsKey(DEFINITE_DUE_DATE))
          task.setValue(Task.DUE_DATE, values.getAsLong(DEFINITE_DUE_DATE));
        if (values.containsKey(IMPORTANCE))
          task.setValue(Task.IMPORTANCE, values.getAsInteger(IMPORTANCE));
        if (values.containsKey(COMPLETED))
          task.setValue(
              Task.COMPLETION_DATE, values.getAsBoolean(COMPLETED) ? DateUtilities.now() : 0);

        // map selection criteria
        String criteria =
            selection
                .replace(NAME, Task.TITLE.name)
                .replace(PREFERRED_DUE_DATE, Task.DUE_DATE.name)
                .replace(DEFINITE_DUE_DATE, Task.DUE_DATE.name)
                .replace(IDENTIFIER, Task.ID.name)
                .replace(ID, Task.ID.name)
                .replace(IMPORTANCE, Task.IMPORTANCE.name);

        return taskService.updateBySelection(criteria, selectionArgs, task);

      case URI_TAGS:
        throw new UnsupportedOperationException("tags updating: not yet");

      default:
        throw new IllegalStateException("Unrecognized URI:" + uri);
    }
  }
Пример #30
0
  /**
   * Check whether the user has changed this property value and it should be stored for saving in
   * the database
   */
  protected synchronized <TYPE> boolean shouldSaveValue(Property<TYPE> property, TYPE newValue) {

    // we've already decided to save it, so overwrite old value
    if (setValues.containsKey(property.getColumnName())) {
      return true;
    }

    // values contains this key, we should check it out
    if (values != null && values.containsKey(property.getColumnName())) {
      TYPE value = getValue(property);
      if (value == null) {
        if (newValue == null) {
          return false;
        }
      } else if (value.equals(newValue)) {
        return false;
      }
    }

    // otherwise, good to save
    return true;
  }