Exemple #1
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());
  }
Exemple #2
0
 public Msg(ContentValues values) {
   msgId = values.getAsLong("msgId");
   talker = values.getAsString("talker");
   content = values.getAsString("content");
   type = values.getAsInteger("type");
   Integer isSend = values.getAsInteger("isSend");
   this.isSend = isSend != null && isSend == 1;
   if (content != null) {
     isRE = content.contains("领取红包") && content.contains("微信红包") && content.contains("查看红包");
   }
 }
Exemple #3
0
  public final void createFromContentValue(ContentValues args) {
    Integer tmp_i;
    String tmp_s;
    Long tmp_l;
    Boolean tmp_b;

    tmp_s = args.getAsString(FIELD_FROM);
    if (tmp_s != null) {
      from = tmp_s;
    }
    tmp_s = args.getAsString(FIELD_TO);
    if (tmp_s != null) {
      to = tmp_s;
    }
    tmp_s = args.getAsString(FIELD_CONTACT);
    if (tmp_s != null) {
      contact = tmp_s;
    }
    tmp_s = args.getAsString(FIELD_BODY);
    if (tmp_s != null) {
      body = tmp_s;
    }
    tmp_s = args.getAsString(FIELD_MIME_TYPE);
    if (tmp_s != null) {
      mimeType = tmp_s;
    }
    tmp_l = args.getAsLong(FIELD_DATE);
    if (tmp_l != null) {
      date = tmp_l;
    }
    tmp_i = args.getAsInteger(FIELD_TYPE);
    if (tmp_i != null) {
      type = tmp_i;
    }
    tmp_i = args.getAsInteger(FIELD_STATUS);
    if (tmp_i != null) {
      status = tmp_i;
    }
    tmp_b = args.getAsBoolean(FIELD_READ);
    if (tmp_b != null) {
      read = tmp_b;
    }

    tmp_s = args.getAsString(FIELD_FROM_FULL);
    if (tmp_s != null) {
      fullFrom = tmp_s;
    }

    tmp_i = args.getAsInteger(FIELD_DATA_DOWNLOADED);
    if (tmp_i != null) {
      data_downloaded = tmp_i;
    }
  }
Exemple #4
0
  @Override
  public Produto contentValuesParaEntidade(ContentValues contentValues) {

    Produto pro = new Produto();

    pro.setId(contentValues.getAsInteger(COLUNA_ID));
    pro.setNome(contentValues.getAsString(COLUNA_NOME));
    pro.setValor(contentValues.getAsDouble(COLUNA_VALOR));
    pro.setId_fornecedor(contentValues.getAsInteger(COLUNA_ID_FORNECEDOR));

    return pro;
  }
 @Test
 public void testMessageToContentValuesWithCalllog() throws Exception {
   PersonRecord record = new PersonRecord(1, "The name", "*****@*****.**", "+1234");
   when(personLookup.lookupPerson("+12121")).thenReturn(record);
   final ContentValues values = messageConverter.messageToContentValues(createCallLogMessage());
   assertThat(values.getAsString(CallLog.Calls.NUMBER)).isEqualTo("+12121");
   assertThat(values.getAsString(CallLog.Calls.TYPE)).isEqualTo("3");
   assertThat(values.getAsString(CallLog.Calls.DATE)).isEqualTo("1419163218194");
   assertThat(values.getAsLong(CallLog.Calls.DURATION)).isEqualTo(44L);
   assertThat(values.getAsInteger(CallLog.Calls.NEW)).isEqualTo(0);
   assertThat(values.getAsString(CallLog.Calls.CACHED_NAME)).isEqualTo("The name");
   assertThat(values.getAsInteger(CallLog.Calls.CACHED_NUMBER_TYPE)).isEqualTo(-2);
 }
  private Uri savePlayer(ContentValues values) {
    ContentValues player = new ContentValues();
    player.put(Provider.Players._ID, Defaults.AUTOGENERATED_ID);
    player.put(Provider.Players.NAME, values.getAsString(Provider.Players.NAME));
    player.put(Provider.Players.PASS, values.getAsString(Provider.Players.PASS));
    player.put(Provider.Players.WON, values.getAsInteger(Provider.Players.WON));
    player.put(Provider.Players.PLAYED, values.getAsInteger(Provider.Players.PLAYED));
    player.put(Provider.Players.COUNTRY, values.getAsString(Provider.Players.COUNTRY));
    player.put(Provider.Players.BIRTH, values.getAsString(Provider.Players.BIRTH));

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    long newId = db.insert(Provider.Players.TABLE_NAME, Defaults.NO_NULL_COLUMN_HACK, player);
    return ContentUris.withAppendedId(CONTENT_URI, newId);
  }
 @Override
 public void endElement(String nsUri, String lName, String rawName) throws SAXException {
   if (curTag.equals(LOGIN_TAG)) {
     data.put("login", curContent.toString());
   } else if (curTag.equals(INFO_TAG)) {
     data.put("info", curContent.toString());
   } else if (curTag.equals(MESSAGE_TAG)) {
     data.put("message", curContent.toString());
   }
   if (lName.equals(POST_TAG)) {
     Uri getUri =
         ContentUris.withAppendedId(
             Uri.withAppendedPath(
                 PostsProvider.Posts.CONTENT_ID_URI_BASE, data.getAsString("board")),
             data.getAsInteger("id"));
     Cursor getCursor = getContentResolver().query(getUri, ID_COL, null, null, null);
     if (lastId < data.getAsLong("id")) {
       lastId = data.getAsLong("id");
     }
     if (getCursor.moveToFirst()) {
       getCursor.close();
       return;
     }
     posts[index++] = data;
     getCursor.close();
   }
 }
  /** Keeps the direct messages table at acceptable size */
  private void purgeDMs(ContentValues cv) {

    // in the content values we find which buffer(s) to purge
    int bufferFlags = cv.getAsInteger(DirectMessages.COL_BUFFER);

    if ((bufferFlags & DirectMessages.BUFFER_MESSAGES) != 0) {
      Log.d(TAG, "purging local direct messages buffer");
      purgeBuffer(DirectMessages.BUFFER_MESSAGES, Constants.MESSAGES_BUFFER_SIZE);
    }

    if ((bufferFlags & DirectMessages.BUFFER_DISASTER_OTHERS) != 0) {
      Log.d(TAG, "purging relay direct messages buffer");
      purgeBuffer(DirectMessages.BUFFER_DISASTER_OTHERS, Constants.DISASTERDM_BUFFER_SIZE);
    }

    if ((bufferFlags & DirectMessages.BUFFER_DISASTER_ME) != 0) {
      Log.d(TAG, "purging relay direct messages buffer");
      purgeBuffer(DirectMessages.BUFFER_DISASTER_ME, Constants.DISASTERDM_BUFFER_SIZE);
    }

    if ((bufferFlags & DirectMessages.BUFFER_MYDISASTER) != 0) {
      Log.d(TAG, "purging local direct messages buffer");
      purgeBuffer(DirectMessages.BUFFER_MYDISASTER, Constants.MYDISASTERDM_BUFFER_SIZE);
    }
  }
  /** 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);
    }
  }
 private String getInsertSQL(ContentValues next) {
   return "INSERT INTO devices ("
       + Devices.NAME
       + ", "
       + Devices.LOCATION
       + ", "
       + Devices.DEVICE_TYPE
       + ", "
       + Devices.POWER
       + ", "
       + Devices.REST_ID
       + ", "
       + Devices.CREATED_AT
       + ", "
       + Devices.UPDATED_AT
       + ") "
       + "values ('"
       + next.getAsString(Devices.NAME)
       + "', '"
       + next.getAsString(Devices.LOCATION)
       + "', '"
       + next.getAsString(Devices.DEVICE_TYPE)
       + "', '"
       + next.getAsBoolean(Devices.POWER)
       + "', '"
       + next.getAsInteger(Devices.REST_ID)
       + "', '"
       + next.get(Devices.CREATED_AT)
       + "', '"
       + next.get(Devices.UPDATED_AT)
       + "'"
       + ")";
 }
Exemple #11
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);
  }
Exemple #12
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;
  }
  public User contentValuesUser(ContentValues contentValues) {
    User user = new User();

    user.setPassword(contentValues.getAsString(PASSWORD_COLUMN));
    user.setUsername(contentValues.getAsString(USERNAME_COLUMN));
    user.setName(contentValues.getAsString(NAME_COLUMN));
    user.setCredits(contentValues.getAsInteger(CREDITS_COLUMN));

    return user;
  }
  /**
   * Sets data members contained in a ContentValue object. Note, not all members may be set as this
   * will be dependent on the client usage and therefore null and value checks are recommended
   *
   * @param values
   */
  public void setValues(ContentValues values) {
    if (values.containsKey(MessageContract.Message._ID))
      mId = values.getAsLong(MessageContract.Message._ID);
    final String messageUriString = values.getAsString(MessageContract.Message.ENTITY_URI);
    mEntityUri = !TextUtils.isEmpty(messageUriString) ? Uri.parse(messageUriString) : null;

    // Long can be null need to check
    if (values.containsKey(MessageContract.Message.ACCOUNT_ID)) {
      mAccountId = values.getAsLong(MessageContract.Message.ACCOUNT_ID);
    }
    // Long can be null need to check
    if (values.containsKey(MessageContract.Message.TIMESTAMP)) {
      mTimeStamp = values.getAsLong(MessageContract.Message.TIMESTAMP);
    }
    // Long can be null need to check
    if (values.containsKey(MessageContract.Message.FOLDER_ID)) {
      mFolderId = values.getAsLong(MessageContract.Message.FOLDER_ID);
    }

    if (values.containsKey(MessageContract.Message.STATE)) {
      mState = values.getAsInteger(MessageContract.Message.STATE);
    }

    if (values.containsKey(MessageContract.Message.DIRTY)) {
      mIsDirty = values.getAsInteger(MessageContract.Message.DIRTY) == 1 ? true : false;
    }

    if (values.containsKey(MessageContract.Message.DELETED)) {
      mIsDeleted = values.getAsInteger(MessageContract.Message.DELETED) == 1 ? true : false;
    }

    mMimeType = values.getAsString(MessageContract.Message.MIME_TYPE);
    mConversationId = values.getAsString(MessageContract.Message.CONVERSATION_ID);
    mSender = values.getAsString(MessageContract.Message.SENDER);
    mSubject = values.getAsString(MessageContract.Message.SUBJECT);
    mRemoteId = values.getAsString(MessageContract.Message.REMOTE_ID);
    mSyncData1 = values.getAsString(MessageContract.Message.SYNC_DATA1);
    mSyncData2 = values.getAsString(MessageContract.Message.SYNC_DATA2);
    mSyncData3 = values.getAsString(MessageContract.Message.SYNC_DATA3);
    mSyncData4 = values.getAsString(MessageContract.Message.SYNC_DATA4);
    mSyncData5 = values.getAsString(MessageContract.Message.SYNC_DATA5);
  }
Exemple #15
0
 @Override
 public Uri insert(Uri uri, ContentValues values) {
   removeRepoFields(values);
   validateFields(DataColumns.ALL, values);
   write().insertOrThrow(getTableName(), null, values);
   if (!isApplyingBatch()) {
     getContext().getContentResolver().notifyChange(uri, null);
   }
   return getContentUri(
       values.getAsString(DataColumns.PACKAGE_NAME),
       values.getAsInteger(DataColumns.VERSION_CODE));
 }
 private static int getDownloadManagerPendingIdFromWordlistId(
     final Context context, final String clientId, final String wordlistId) {
   final SQLiteDatabase db = MetadataDbHelper.getDb(context, clientId);
   final ContentValues wordlistValues =
       MetadataDbHelper.getContentValuesOfLatestAvailableWordlistById(db, wordlistId);
   if (null == wordlistValues) {
     // We don't know anything about a word list with this id. Bug? This should never
     // happen, but still return to prevent a crash.
     Log.e(TAG, "Unexpected word list ID: " + wordlistId);
     return NOT_A_DOWNLOADMANAGER_PENDING_ID;
   }
   return wordlistValues.getAsInteger(MetadataDbHelper.PENDINGID_COLUMN);
 }
  public void setValues(ContentValues values) {

    mId = values.getAsLong(MessageContact._ID);
    mName = values.getAsString(MessageContact.NAME);
    mAddress = values.getAsString(MessageContact.ADDRESS);

    if (values.containsKey(MessageContact.ADDRESS_TYPE)) {
      mAddressType = values.getAsInteger(MessageContact.ADDRESS_TYPE);
    }

    if (values.containsKey(MessageContact.FIELD_TYPE)) {
      mFieldType = values.getAsInteger(MessageContact.FIELD_TYPE);
    }

    if (values.containsKey(MessageContact.MESSAGE_ID)) {
      mMessageId = values.getAsInteger(MessageContact.MESSAGE_ID);
    }

    if (values.containsKey(MessageContact.ACCOUNT_ID)) {
      mAccountId = values.getAsInteger(MessageContact.ACCOUNT_ID);
    }
  }
 public static Movie fromContentValues(ContentValues values) {
   Movie m = new Movie();
   m.id = values.getAsLong(MovieContract.MovieEntry._ID);
   m.title = values.getAsString(MovieContract.MovieEntry.COLUMN_NAME_TITLE);
   m.overview = values.getAsString(MovieContract.MovieEntry.COLUMN_OVERVIEW);
   m.posterUrl = values.getAsString(MovieContract.MovieEntry.COLUMN_POSTER_PATH);
   m.releaseDate = values.getAsString(MovieContract.MovieEntry.COLUMN_RELEASE_DATE);
   m.rating = values.getAsDouble(MovieContract.MovieEntry.COLUMN_VOTE_AVERAGE);
   m.popularity = values.getAsDouble(MovieContract.MovieEntry.COLUMN_POPULARITY);
   m.isFavorite =
       values.getAsInteger(MovieContract.MovieEntry.COLUMN_FAVORITE) == 0 ? false : true;
   return m;
 }
 @Override
 public Uri insert(Uri uri, ContentValues values) {
   // TODO Auto-generated method stub
   int rowID =
       mManager.addDream(
           new Date(values.getAsString(Dreams.TIME)),
           values.getAsInteger(Dreams.PART),
           values.getAsString(Dreams.TITLE),
           values.getAsString(Dreams.DESCRIPTION),
           values.getAsString(Dreams.TAGS),
           values.getAsBoolean(Dreams.EROTIC));
   return ContentUris.withAppendedId(uri, rowID);
 }
Exemple #20
0
  /**
   * Initialize a FillUp based on a set of ContentValues. This is likely to be used when saving a
   * new FillUp into the database. By initializing the data before sending, we can perform sanity
   * checks to make sure that there isn't anything weird with the data before we commit it to the
   * database.
   *
   * @param values A ContentValues mapping of the data to load.
   */
  public FillUp(ContentValues values) {
    this((CalculationEngine) null);

    Double price = values.getAsDouble(PRICE);
    if (price != null) {
      setPrice(price);
    }

    Double odometer = values.getAsDouble(ODOMETER);
    if (odometer != null) {
      setOdometer(odometer);
    }

    Long time = values.getAsLong(DATE);
    if (time != null) {
      setDate(time);
    }

    Double amount = values.getAsDouble(AMOUNT);
    if (amount != null) {
      setAmount(amount);
    }

    Double latitude = values.getAsDouble(LATITUDE);
    if (latitude != null) {
      setLatitude(latitude);
    }

    Double longitude = values.getAsDouble(LONGITUDE);
    if (longitude != null) {
      setLongitude(longitude);
    }

    String comment = values.getAsString(COMMENT);
    if (comment != null) {
      setComment(comment);
    }

    Long vehicleId = values.getAsLong(VEHICLE_ID);
    if (vehicleId != null) {
      setVehicleId(vehicleId);
    }

    Integer isPartial = values.getAsInteger(PARTIAL);
    if (isPartial != null) {
      setPartial(isPartial == 1);
    }
  }
  @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);
    }
  }
  private void sendPost() {
    if (replyData == null || replyData.getAsInteger(AwfulMessage.ID) == null) {
      // TODO: if this ever happens, the ID never gets set (and causes an NPE in SendPostRequest) -
      // handle this in a better way?
      // Could use the mThreadId value, but that might be incorrect at this point and post to the
      // wrong thread? Is null reply data an exceptional event?
      Log.e(TAG, "No reply data in sendPost() - no thread ID to post to!");
      Activity activity = getActivity();
      if (activity != null) {
        Toast.makeText(activity, "Unknown thread ID - can't post!", Toast.LENGTH_LONG).show();
      }
      return;
    }
    ContentValues cv = new ContentValues(replyData);
    String content = mMessage.getText().toString().trim();
    if (TextUtils.isEmpty(content)) {
      if (mDialog != null) {
        mDialog.dismiss();
      }
      displayAlert(R.string.message_empty, R.string.message_empty_subtext, 0);
      return;
    }
    if (!TextUtils.isEmpty(mFileAttachment)) {
      cv.put(AwfulMessage.REPLY_ATTACHMENT, mFileAttachment);
    }
    if (postSignature) {
      cv.put(AwfulMessage.REPLY_SIGNATURE, Constants.YES);
      System.out.println(AwfulMessage.REPLY_SIGNATURE + " " + Constants.YES);
    }
    if (disableEmots) {
      cv.put(AwfulMessage.REPLY_DISABLE_SMILIES, Constants.YES);
      System.out.println(AwfulMessage.REPLY_DISABLE_SMILIES + " " + Constants.YES);
    }
    cv.put(AwfulMessage.REPLY_CONTENT, content);
    AwfulRequest.AwfulResultCallback<Void> postCallback =
        new AwfulRequest.AwfulResultCallback<Void>() {
          @Override
          public void success(Void result) {
            if (mDialog != null) {
              mDialog.dismiss();
              mDialog = null;
            }
            sendSuccessful = true;
            mContentResolver.delete(
                AwfulMessage.CONTENT_URI_REPLY,
                AwfulMessage.ID + "=?",
                AwfulProvider.int2StrArray(mThreadId));

            final Activity activity = getActivity();
            if (activity != null) {
              Toast.makeText(activity, activity.getString(R.string.post_sent), Toast.LENGTH_LONG)
                  .show();
              if (mReplyType == AwfulMessage.TYPE_EDIT) {
                activity.setResult(mPostId);
              } else {
                activity.setResult(RESULT_POSTED);
              }
            }
            leave();
          }

          @Override
          public void failure(VolleyError error) {
            if (mDialog != null) {
              mDialog.dismiss();
              mDialog = null;
            }
            saveReply();
          }
        };
    switch (mReplyType) {
      case AwfulMessage.TYPE_QUOTE:
      case AwfulMessage.TYPE_NEW_REPLY:
        queueRequest(new SendPostRequest(getActivity(), cv).build(this, postCallback));
        break;
      case AwfulMessage.TYPE_EDIT:
        queueRequest(new SendEditRequest(getActivity(), cv).build(this, postCallback));
        break;
      default:
        getActivity().finish();
    }
  }
Exemple #23
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;
  }
  /** 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;
  }
  public void updateProvider(
      Feed feed, Long syncLocalId, Entry entry, ContentProvider provider, Object info)
      throws ParseException {
    SyncInfo syncInfo = (SyncInfo) info;
    EventEntry event = (EventEntry) entry;

    ContentValues map = new ContentValues();

    // use the calendar's timezone, if provided in the feed.
    // this overwrites whatever was in the db.
    if ((feed != null) && (feed instanceof EventsFeed)) {
      EventsFeed eventsFeed = (EventsFeed) feed;
      syncInfo.calendarTimezone = eventsFeed.getTimezone();
    }

    if (entry.isDeleted()) {
      deletedEntryToContentValues(syncLocalId, event, map);
      if (Config.LOGV) {
        Log.v(TAG, "Deleting entry: " + map);
      }
      provider.insert(Events.DELETED_CONTENT_URI, map);
      return;
    }

    int entryState = entryToContentValues(event, syncLocalId, map, syncInfo);

    if (entryState == ENTRY_DELETED) {
      if (Config.LOGV) {
        Log.v(TAG, "Got deleted entry from server: " + map);
      }
      provider.insert(Events.DELETED_CONTENT_URI, map);
    } else if (entryState == ENTRY_OK) {
      if (Config.LOGV) {
        Log.v(TAG, "Got entry from server: " + map);
      }
      Uri result = provider.insert(Events.CONTENT_URI, map);
      long rowId = ContentUris.parseId(result);
      // handle the reminders for the event
      Integer hasAlarm = map.getAsInteger(Events.HAS_ALARM);
      if (hasAlarm != null && hasAlarm == 1) {
        // reminders should not be null
        Vector alarms = event.getReminders();
        if (alarms == null) {
          Log.e(TAG, "Have an alarm but do not have any reminders " + "-- should not happen.");
          throw new IllegalStateException("Have an alarm but do not have any reminders");
        }
        Enumeration reminders = alarms.elements();
        while (reminders.hasMoreElements()) {
          ContentValues reminderValues = new ContentValues();
          reminderValues.put(Calendar.Reminders.EVENT_ID, rowId);

          Reminder reminder = (Reminder) reminders.nextElement();
          byte method = reminder.getMethod();
          switch (method) {
            case Reminder.METHOD_DEFAULT:
              reminderValues.put(Calendar.Reminders.METHOD, Calendar.Reminders.METHOD_DEFAULT);
              break;
            case Reminder.METHOD_ALERT:
              reminderValues.put(Calendar.Reminders.METHOD, Calendar.Reminders.METHOD_ALERT);
              break;
            case Reminder.METHOD_EMAIL:
              reminderValues.put(Calendar.Reminders.METHOD, Calendar.Reminders.METHOD_EMAIL);
              break;
            case Reminder.METHOD_SMS:
              reminderValues.put(Calendar.Reminders.METHOD, Calendar.Reminders.METHOD_SMS);
              break;
            default:
              // should not happen.  return false?  we'd have to
              // roll back the event.
              Log.e(TAG, "Unknown reminder method: " + method + " should not happen!");
          }

          int minutes = reminder.getMinutes();
          reminderValues.put(
              Calendar.Reminders.MINUTES,
              minutes == Reminder.MINUTES_DEFAULT ? Calendar.Reminders.MINUTES_DEFAULT : minutes);

          if (provider.insert(Calendar.Reminders.CONTENT_URI, reminderValues) == null) {
            throw new ParseException("Unable to insert reminders.");
          }
        }
      }

      // handle attendees for the event
      Vector attendees = event.getAttendees();
      Enumeration attendeesEnum = attendees.elements();
      while (attendeesEnum.hasMoreElements()) {
        Who who = (Who) attendeesEnum.nextElement();
        ContentValues attendeesValues = new ContentValues();
        attendeesValues.put(Calendar.Attendees.EVENT_ID, rowId);
        attendeesValues.put(Calendar.Attendees.ATTENDEE_NAME, who.getValue());
        attendeesValues.put(Calendar.Attendees.ATTENDEE_EMAIL, who.getEmail());

        byte status;
        switch (who.getStatus()) {
          case Who.STATUS_NONE:
            status = Calendar.Attendees.ATTENDEE_STATUS_NONE;
            break;
          case Who.STATUS_INVITED:
            status = Calendar.Attendees.ATTENDEE_STATUS_INVITED;
            break;
          case Who.STATUS_ACCEPTED:
            status = Calendar.Attendees.ATTENDEE_STATUS_ACCEPTED;
            break;
          case Who.STATUS_TENTATIVE:
            status = Calendar.Attendees.ATTENDEE_STATUS_TENTATIVE;
            break;
          case Who.STATUS_DECLINED:
            status = Calendar.Attendees.ATTENDEE_STATUS_DECLINED;
            break;
          default:
            Log.w(TAG, "Unknown attendee status " + who.getStatus());
            status = Calendar.Attendees.ATTENDEE_STATUS_NONE;
        }
        attendeesValues.put(Calendar.Attendees.ATTENDEE_STATUS, status);
        byte rel;
        switch (who.getRelationship()) {
          case Who.RELATIONSHIP_NONE:
            rel = Calendar.Attendees.RELATIONSHIP_NONE;
            break;
          case Who.RELATIONSHIP_ORGANIZER:
            rel = Calendar.Attendees.RELATIONSHIP_ORGANIZER;
            break;
          case Who.RELATIONSHIP_ATTENDEE:
            rel = Calendar.Attendees.RELATIONSHIP_ATTENDEE;
            break;
          case Who.RELATIONSHIP_PERFORMER:
            rel = Calendar.Attendees.RELATIONSHIP_PERFORMER;
            break;
          case Who.RELATIONSHIP_SPEAKER:
            rel = Calendar.Attendees.RELATIONSHIP_SPEAKER;
            break;
          default:
            Log.w(TAG, "Unknown attendee relationship " + who.getRelationship());
            rel = Calendar.Attendees.RELATIONSHIP_NONE;
        }

        attendeesValues.put(Calendar.Attendees.ATTENDEE_RELATIONSHIP, rel);

        byte type;
        switch (who.getType()) {
          case Who.TYPE_NONE:
            type = Calendar.Attendees.TYPE_NONE;
            break;
          case Who.TYPE_REQUIRED:
            type = Calendar.Attendees.TYPE_REQUIRED;
            break;
          case Who.TYPE_OPTIONAL:
            type = Calendar.Attendees.TYPE_OPTIONAL;
            break;
          default:
            Log.w(TAG, "Unknown attendee type " + who.getType());
            type = Calendar.Attendees.TYPE_NONE;
        }
        attendeesValues.put(Calendar.Attendees.ATTENDEE_TYPE, type);
        if (provider.insert(Calendar.Attendees.CONTENT_URI, attendeesValues) == null) {
          throw new ParseException("Unable to insert attendees.");
        }
      }

      // handle the extended properties for the event
      Integer hasExtendedProperties = map.getAsInteger(Events.HAS_EXTENDED_PROPERTIES);
      if (hasExtendedProperties != null && hasExtendedProperties.intValue() != 0) {
        // extended properties should not be null
        // TODO: make the extended properties a bit more OO?
        Hashtable extendedProperties = event.getExtendedProperties();
        if (extendedProperties == null) {
          Log.e(
              TAG,
              "Have extendedProperties but do not have any properties" + "-- should not happen.");
          throw new IllegalStateException("Have extendedProperties but do not have any properties");
        }
        Enumeration propertyNames = extendedProperties.keys();
        while (propertyNames.hasMoreElements()) {
          String propertyName = (String) propertyNames.nextElement();
          String propertyValue = (String) extendedProperties.get(propertyName);
          ContentValues extendedPropertyValues = new ContentValues();
          extendedPropertyValues.put(Calendar.ExtendedProperties.EVENT_ID, rowId);
          extendedPropertyValues.put(Calendar.ExtendedProperties.NAME, propertyName);
          extendedPropertyValues.put(Calendar.ExtendedProperties.VALUE, propertyValue);
          if (provider.insert(Calendar.ExtendedProperties.CONTENT_URI, extendedPropertyValues)
              == null) {
            throw new ParseException("Unable to insert extended properties.");
          }
        }
      }
    } else {
      // If the DTSTART == -1, then the date was out of range.  We don't
      // need to throw a ParseException because the user can create
      // dates on the web that we can't handle on the phone.  For
      // example, events with dates before Dec 13, 1901 can be created
      // on the web but cannot be handled on the phone.
      Long dtstart = map.getAsLong(Events.DTSTART);
      if (dtstart != null && dtstart == -1) {
        return;
      }

      if (Config.LOGV) {
        Log.v(TAG, "Got invalid entry from server: " + map);
      }
      throw new ParseException("Got invalid entry from server: " + map);
    }
  }
  /** Inserts a row in the database */
  @Override
  public Uri insert(final Uri uri, final ContentValues values) {
    //		checkInsertPermissions(values);
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    // note we disallow inserting into ALL_DOWNLOADS
    int match = sURIMatcher.match(uri);
    if (match != MY_DOWNLOADS) {
      Log.d(Constants.TAG, "calling insert on an unknown/invalid URI: " + uri);
      throw new IllegalArgumentException("Unknown/Invalid URI " + uri);
    }

    ContentValues filteredValues = new ContentValues();

    copyString(Downloads.COLUMN_URI, values, filteredValues);
    copyString(Downloads.COLUMN_APP_DATA, values, filteredValues);
    copyBoolean(Downloads.COLUMN_NO_INTEGRITY, values, filteredValues);
    copyString(Downloads.COLUMN_FILE_NAME_HINT, values, filteredValues);
    copyString(Downloads.COLUMN_MIME_TYPE, values, filteredValues);

    copyBoolean(Downloads.COLUMN_IS_PUBLIC_API, values, filteredValues);
    boolean isPublicApi = values.getAsBoolean(Downloads.COLUMN_IS_PUBLIC_API) == Boolean.TRUE;

    Integer dest = values.getAsInteger(Downloads.COLUMN_DESTINATION);
    if (dest != null) {
      if (dest != Downloads.DESTINATION_EXTERNAL && dest != Downloads.DESTINATION_FILE_URI) {
        throw new SecurityException("unauthorized destination code");
      }
      if (dest == Downloads.DESTINATION_FILE_URI) {
        getContext()
            .enforcePermission(
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Binder.getCallingPid(),
                Binder.getCallingUid(),
                "need WRITE_EXTERNAL_STORAGE permission to use DESTINATION_FILE_URI");
        checkFileUriDestination(values);
      }
      filteredValues.put(Downloads.COLUMN_DESTINATION, dest);
    }
    Integer vis = values.getAsInteger(Downloads.COLUMN_VISIBILITY);
    if (vis == null) {
      if (dest == Downloads.DESTINATION_EXTERNAL) {
        filteredValues.put(
            Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
      } else {
        filteredValues.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_HIDDEN);
      }
    } else {
      filteredValues.put(Downloads.COLUMN_VISIBILITY, vis);
    }
    copyInteger(Downloads.COLUMN_CONTROL, values, filteredValues);
    filteredValues.put(Downloads.COLUMN_STATUS, Downloads.STATUS_PENDING);
    filteredValues.put(Downloads.COLUMN_LAST_MODIFICATION, mSystemFacade.currentTimeMillis());

    String pckg = values.getAsString(Downloads.COLUMN_NOTIFICATION_PACKAGE);
    String clazz = values.getAsString(Downloads.COLUMN_NOTIFICATION_CLASS);
    if (pckg != null && (clazz != null || isPublicApi)) {
      int uid = Binder.getCallingUid();
      try {
        if (uid == 0 || mSystemFacade.userOwnsPackage(uid, pckg)) {
          filteredValues.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, pckg);
          if (clazz != null) {
            filteredValues.put(Downloads.COLUMN_NOTIFICATION_CLASS, clazz);
          }
        }
      } catch (PackageManager.NameNotFoundException ex) {
        /* ignored for now */
      }
    }
    copyString(Downloads.COLUMN_NOTIFICATION_EXTRAS, values, filteredValues);
    copyString(Downloads.COLUMN_COOKIE_DATA, values, filteredValues);
    copyString(Downloads.COLUMN_USER_AGENT, values, filteredValues);
    copyString(Downloads.COLUMN_REFERER, values, filteredValues);
    if (true /*
              * getContext().checkCallingPermission(
              * Downloads.PERMISSION_ACCESS_ADVANCED) ==
              * PackageManager.PERMISSION_GRANTED
              */) {
      copyInteger(Downloads.COLUMN_OTHER_UID, values, filteredValues);
    }
    filteredValues.put(Constants.UID, Binder.getCallingUid());
    if (Binder.getCallingUid() == 0) {
      copyInteger(Constants.UID, values, filteredValues);
    }
    copyStringWithDefault(Downloads.COLUMN_TITLE, values, filteredValues, "");
    copyStringWithDefault(Downloads.COLUMN_DESCRIPTION, values, filteredValues, "");
    filteredValues.put(Downloads.COLUMN_TOTAL_BYTES, -1);
    filteredValues.put(Downloads.COLUMN_CURRENT_BYTES, 0);

    if (values.containsKey(Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI)) {
      copyBoolean(Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, values, filteredValues);
    } else {
      // by default, make external downloads visible in the UI
      boolean isExternal = (dest == null || dest == Downloads.DESTINATION_EXTERNAL);
      filteredValues.put(Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, isExternal);
    }

    if (isPublicApi) {
      copyInteger(Downloads.COLUMN_ALLOWED_NETWORK_TYPES, values, filteredValues);
      copyBoolean(Downloads.COLUMN_ALLOW_ROAMING, values, filteredValues);
    }

    if (Constants.LOGVV) {
      Log.v(
          Constants.TAG,
          "initiating download with UID " + filteredValues.getAsInteger(Constants.UID));
      if (filteredValues.containsKey(Downloads.COLUMN_OTHER_UID)) {
        Log.v(
            Constants.TAG, "other UID " + filteredValues.getAsInteger(Downloads.COLUMN_OTHER_UID));
      }
    }

    Context context = getContext();
    context.startService(new Intent(context, DownloadService.class));

    long rowID = db.insert(DB_TABLE, null, filteredValues);
    if (rowID == -1) {
      Log.d(Constants.TAG, "couldn't insert into downloads database");
      return null;
    }

    insertRequestHeaders(db, rowID, values);
    context.startService(new Intent(context, DownloadService.class));
    notifyContentChanged(uri, match);
    return ContentUris.withAppendedId(Downloads.CONTENT_URI, rowID);
  }
 private static final void copyInteger(String key, ContentValues from, ContentValues to) {
   Integer i = from.getAsInteger(key);
   if (i != null) {
     to.put(key, i);
   }
 }
 public CharSequence inflateUsing(Context context, ContentValues values) {
   final Integer type = values.getAsInteger(getTypeColumn());
   final String label = values.getAsString(getLabelColumn());
   return getTypeLabel(context.getResources(), type, label);
 }
  /**
   * Tests reference_articles_delete trigger should be created and work correctly Explains about
   * reference_articles_delete: When we delete a linked_article, reference_articles_delete trigger
   * will check if related reference_article doesn't link to any other linked_articles. It will
   * deletes that reference_article.
   */
  @Test
  public void referenceArticlesDeleteTrigger_shouldBeCreated() {
    ContentValues referenceArticlesValues = TestUtilities.createReferenceArticleValues();
    ContentValues linkedArticleValues = TestUtilities.createLinkedArticleValue();

    int referenceArticleId =
        referenceArticlesValues.getAsInteger(ArticleContract.ReferenceArticles.ARTICLE_ID);
    int referenceId = linkedArticleValues.getAsInteger(ArticleDatabase.LinkedArticles.REFERENCE_ID);

    // Insert a reference_article and a related linked_article into db
    long rowId =
        db.insert(ArticleDatabase.Tables.REFERENCE_ARTICLES, null, referenceArticlesValues);
    assertThat("Unable to Insert a reference_article into the DB", rowId != -1);
    rowId = db.insert(ArticleDatabase.Tables.LINKED_ARTICLES, null, linkedArticleValues);
    assertThat("Unable to Insert a linked_article into the DB", rowId != -1);

    // Query an article to assert that it was already inserted in DB
    cursor =
        db.query(
            ArticleDatabase.Tables.REFERENCE_ARTICLES,
            null,
            ArticleContract.ReferenceArticles.ARTICLE_ID + "=?",
            new String[] {String.valueOf(referenceArticleId)},
            null,
            null,
            null);
    TestUtilities.validateCursor(null, cursor, referenceArticlesValues);

    // Query a linked_article to assert that it was already inserted in DB
    cursor =
        db.query(
            ArticleDatabase.Tables.LINKED_ARTICLES,
            null,
            ArticleDatabase.LinkedArticles.REFERENCE_ID + "=?",
            new String[] {String.valueOf(referenceId)},
            null,
            null,
            null);
    TestUtilities.validateCursor(null, cursor, linkedArticleValues);

    // Finally, delete the linked_article to check that the reference_article also deletes in behind
    int count =
        db.delete(
            ArticleDatabase.Tables.LINKED_ARTICLES,
            ArticleDatabase.LinkedArticles.REFERENCE_ID + "=?",
            new String[] {String.valueOf(referenceId)});
    assertThat(count, is(1));

    cursor =
        db.query(
            ArticleDatabase.Tables.LINKED_ARTICLES,
            null,
            ArticleDatabase.LinkedArticles.REFERENCE_ID + "=?",
            new String[] {String.valueOf(referenceId)},
            null,
            null,
            null);
    assertThat("Error: Delete an article unsuccessful", !cursor.moveToFirst());

    cursor =
        db.query(
            ArticleDatabase.Tables.REFERENCE_ARTICLES,
            null,
            ArticleContract.ReferenceArticles.ARTICLE_ID + "=?",
            new String[] {String.valueOf(referenceArticleId)},
            null,
            null,
            null);
    assertThat("Error: reference_article_delete trigger didn't work.", !cursor.moveToFirst());
  }
  /**
   * Tests articles_videos_delete trigger should be created and work correctly Explains about
   * articles_videos_delete: When we delete an article, articles_videos_delete trigger also delete
   * related videos.
   */
  @Test
  public void articlesVideosDeleteTrigger_shouldBeCreated() {
    ContentValues articleValues = TestUtilities.createArticleValues();
    ContentValues videoValues = TestUtilities.createVideoValue();

    int articleId = articleValues.getAsInteger(ArticleContract.Articles.ARTICLE_ID);
    int videoId = videoValues.getAsInteger(ArticleContract.Videos.VIDEO_ID);

    // Insert an articles and a related video into db
    long rowId = db.insert(ArticleDatabase.Tables.ARTICLES, null, articleValues);
    assertThat("Unable to Insert an article into the DB", rowId != -1);
    rowId = db.insert(ArticleDatabase.Tables.VIDEOS, null, videoValues);
    assertThat("Unable to Insert a video into the DB", rowId != -1);

    // Query an article to assert that it was already inserted in DB
    cursor =
        db.query(
            ArticleDatabase.Tables.ARTICLES,
            null,
            ArticleContract.Articles.ARTICLE_ID + "=?",
            new String[] {String.valueOf(articleId)},
            null,
            null,
            null);
    TestUtilities.validateCursor(null, cursor, articleValues);

    // Query a video to assert that it was already inserted in DB
    cursor =
        db.query(
            ArticleDatabase.Tables.VIDEOS,
            null,
            ArticleContract.Videos.VIDEO_ID + "=?",
            new String[] {String.valueOf(videoId)},
            null,
            null,
            null);
    TestUtilities.validateCursor(null, cursor, videoValues);

    // Finally, delete the article to check that the video also deletes in behind
    int count =
        db.delete(
            ArticleDatabase.Tables.ARTICLES,
            ArticleContract.Articles.ARTICLE_ID + "=?",
            new String[] {String.valueOf(articleId)});
    assertThat(count, is(1));

    cursor =
        db.query(
            ArticleDatabase.Tables.ARTICLES,
            null,
            ArticleContract.Articles.ARTICLE_ID + "=?",
            new String[] {String.valueOf(articleId)},
            null,
            null,
            null);
    assertThat("Error: Delete an article unsuccessful", !cursor.moveToFirst());

    cursor =
        db.query(
            ArticleDatabase.Tables.VIDEOS,
            null,
            ArticleContract.Videos.VIDEO_ID + "=?",
            new String[] {String.valueOf(videoId)},
            null,
            null,
            null);
    assertThat("Error: articles_videos_delete trigger didn't work.", !cursor.moveToFirst());
  }