Example usage for android.content ContentResolver update

List of usage examples for android.content ContentResolver update

Introduction

In this page you can find the example usage for android.content ContentResolver update.

Prototype

public final int update(@RequiresPermission.Write @NonNull Uri uri, @Nullable ContentValues values,
        @Nullable String where, @Nullable String[] selectionArgs) 

Source Link

Document

Update row(s) in a content URI.

Usage

From source file:com.app.uafeed.activity.EditFeedActivity.java

@Override
protected void onDestroy() {
    if (getIntent().getAction().equals(Intent.ACTION_EDIT)) {
        String url = mUrlEditText.getText().toString();
        ContentResolver cr = getContentResolver();

        Cursor cursor = getContentResolver().query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID,
                FeedColumns.URL + Constants.DB_ARG, new String[] { url }, null);

        if (cursor.moveToFirst() && !getIntent().getData().getLastPathSegment().equals(cursor.getString(0))) {
            cursor.close();/*  w ww.  jav a 2 s. c o m*/
            Toast.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Toast.LENGTH_LONG).show();
        } else {
            cursor.close();
            ContentValues values = new ContentValues();

            if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) {
                url = Constants.HTTP_SCHEME + url;
            }
            values.put(FeedColumns.URL, url);

            String name = mNameEditText.getText().toString();

            values.put(FeedColumns.NAME, name.trim().length() > 0 ? name : null);
            values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
            values.put(FeedColumns.FETCH_MODE, 0);
            values.putNull(FeedColumns.ERROR);

            cr.update(getIntent().getData(), values, null, null);
        }
    }

    super.onDestroy();
}

From source file:net.fred.feedex.activity.EditFeedActivity.java

@Override
protected void onDestroy() {
    if (getIntent().getAction().equals(Intent.ACTION_EDIT)) {
        String url = mUrlEditText.getText().toString();
        ContentResolver cr = getContentResolver();

        Cursor cursor = null;//from  w w  w  .  j a v a 2 s  .c o m
        try {
            cursor = getContentResolver().query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID,
                    FeedColumns.URL + Constants.DB_ARG, new String[] { url }, null);

            if (cursor != null && cursor.moveToFirst()
                    && !getIntent().getData().getLastPathSegment().equals(cursor.getString(0))) {
                UiUtils.showMessage(EditFeedActivity.this, R.string.error_feed_url_exists);
            } else {
                ContentValues values = new ContentValues();

                if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) {
                    url = Constants.HTTP_SCHEME + url;
                }
                values.put(FeedColumns.URL, url);

                String name = mNameEditText.getText().toString();

                values.put(FeedColumns.NAME, name.trim().length() > 0 ? name : null);
                values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
                values.put(FeedColumns.FETCH_MODE, 0);
                values.putNull(FeedColumns.ERROR);

                cr.update(getIntent().getData(), values, null, null);
            }
        } catch (Exception ignored) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    super.onDestroy();
}

From source file:org.jsharkey.sky.webservice.WebserviceHelper.java

/**
 * Perform a webservice query to retrieve and store the forecast for the
 * given widget. This call blocks until request is finished and
 * {@link Forecasts#CONTENT_URI} has been updated.
 *//* ww w . j  a v  a  2  s  .c  o  m*/
public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ParseException {

    if (sUserAgent == null) {
        prepareUserAgent(context);
    }

    Uri appWidgetForecasts = Uri.withAppendedPath(appWidgetUri, AppWidgets.TWIG_FORECASTS);

    ContentResolver resolver = context.getContentResolver();

    Cursor cursor = null;
    double lat = Double.NaN;
    double lon = Double.NaN;
    String countryCode = null;

    // Pull exact forecast location from database
    try {
        cursor = resolver.query(appWidgetUri, PROJECTION_APPWIDGET, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            lat = cursor.getDouble(COL_LAT);
            lon = cursor.getDouble(COL_LON);
            countryCode = cursor.getString(COL_COUNTRY_CODE);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    Log.d(TAG, "using country code=" + countryCode);

    // Query webservice for this location
    List<Forecast> forecasts = null;
    if (COUNTRY_US.equals(countryCode)) {
        forecasts = new NoaaSource().getForecasts(lat, lon, days);
    } else {
        forecasts = new MetarSource().getForecasts(lat, lon, days);
    }

    if (forecasts == null || forecasts.size() == 0) {
        throw new ParseException("No forecasts found from webservice query");
    }

    // Purge existing forecasts covered by incoming data, and anything
    // before today
    long lastMidnight = ForecastUtils.getLastMidnight();
    long earliest = Long.MAX_VALUE;
    for (Forecast forecast : forecasts) {
        earliest = Math.min(earliest, forecast.validStart);
    }

    resolver.delete(appWidgetForecasts, ForecastsColumns.VALID_START + " >= " + earliest + " OR "
            + ForecastsColumns.VALID_START + " <= " + lastMidnight, null);

    // Insert any new forecasts found
    ContentValues values = new ContentValues();
    for (Forecast forecast : forecasts) {
        Log.d(TAG, "inserting forecast with validStart=" + forecast.validStart);
        values.clear();
        values.put(ForecastsColumns.VALID_START, forecast.validStart);
        values.put(ForecastsColumns.TEMP_HIGH, forecast.tempHigh);
        values.put(ForecastsColumns.TEMP_LOW, forecast.tempLow);
        values.put(ForecastsColumns.CONDITIONS, forecast.conditions);
        values.put(ForecastsColumns.URL, forecast.url);
        if (forecast.alert) {
            values.put(ForecastsColumns.ALERT, ForecastsColumns.ALERT_TRUE);
        }
        resolver.insert(appWidgetForecasts, values);
    }

    // Mark widget cache as being updated
    values.clear();
    values.put(AppWidgetsColumns.LAST_UPDATED, System.currentTimeMillis());
    resolver.update(appWidgetUri, values, null, null);
}

From source file:com.carlrice.reader.activity.EditFeedActivity.java

@Override
protected void onDestroy() {
    if (getIntent().getAction().equals(Intent.ACTION_EDIT)) {
        String url = mUrlEditText.getText().toString();
        ContentResolver cr = getContentResolver();

        Cursor cursor = null;// ww w  . j  a  v a2 s.  c  o  m
        try {
            cursor = getContentResolver().query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID,
                    FeedColumns.URL + Constants.DB_ARG, new String[] { url }, null);

            if (cursor != null && cursor.moveToFirst()
                    && !getIntent().getData().getLastPathSegment().equals(cursor.getString(0))) {
                Toast.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Toast.LENGTH_LONG).show();
            } else {
                ContentValues values = new ContentValues();

                if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) {
                    url = Constants.HTTP_SCHEME + url;
                }
                values.put(FeedColumns.URL, url);

                String name = mNameEditText.getText().toString();

                values.put(FeedColumns.NAME, name.trim().length() > 0 ? name : null);
                values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
                values.put(FeedColumns.FETCH_MODE, 0);
                values.putNull(FeedColumns.ERROR);

                cr.update(getIntent().getData(), values, null, null);
            }
        } catch (Exception ignored) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    super.onDestroy();
}

From source file:co.nerdart.ourss.activity.EditFeedActivity.java

@Override
protected void onDestroy() {
    if (getIntent().getAction().equals(Intent.ACTION_EDIT)) {
        String url = mUrlEditText.getText().toString();
        ContentResolver cr = getContentResolver();

        Cursor cursor = getContentResolver().query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID,
                FeedColumns.URL + Constants.DB_ARG, new String[] { url }, null);

        if (cursor.moveToFirst() && !getIntent().getData().getLastPathSegment().equals(cursor.getString(0))) {
            cursor.close();/* ww  w  .java2  s .  c o m*/
            //Toast.makeText(EditFeedActivity.this, R.string.error_feed_url_exists,
            //      Toast.LENGTH_LONG).show();
            Crouton.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Style.INFO);
        } else {
            cursor.close();
            ContentValues values = new ContentValues();

            if (!url.startsWith(Constants.HTTP) && !url.startsWith(Constants.HTTPS)) {
                url = Constants.HTTP + url;
            }
            values.put(FeedColumns.URL, url);

            String name = mNameEditText.getText().toString();

            values.put(FeedColumns.NAME, name.trim().length() > 0 ? name : null);
            values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
            values.put(FeedColumns.FETCH_MODE, 0);
            values.putNull(FeedColumns.ERROR);

            cr.update(getIntent().getData(), values, null, null);
            if (!name.equals(mPreviousName)) {
                cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
            }
        }
    }

    super.onDestroy();
}

From source file:com.example.mydemos.view.RingtonePickerActivity.java

private void setDefaultRingtone() {
    final Uri musicDefault = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
    final String musicTitle = MediaStore.Audio.AudioColumns.TITLE;
    final String musicId = MediaStore.Audio.Media._ID;
    final String musicName = MediaStore.Audio.AudioColumns.DISPLAY_NAME;

    // Get a ContentResovler, 
    // so that we can read the music information form SD card.
    ContentResolver contentResolver = getContentResolver();
    Uri uri = null;/*from  w w  w  .j  a  va2 s  . c o m*/
    String ringtone = "AA_Preo_ringtone.ogg";
    Cursor cursor = contentResolver.query(musicDefault, new String[] { musicId, musicName },
            musicName + " LIKE ?", new String[] { ringtone }, null);
    // If cursor has a recode, we support that we find the music.
    if (cursor.moveToNext()) {
        // Get the music id.
        int position = cursor.getInt(cursor.getColumnIndex(musicId));
        uri = Uri.withAppendedPath(musicDefault, "/" + position);
        Log.d("test", uri.toString());
    }
    // Finish our query work.
    cursor.close();

    if (uri != null) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.AudioColumns.ALBUM_ARTIST, "first");
        contentResolver.update(uri, values, null, null);
    }

    //        defaultView = getLayoutInflater().inflate(
    //              R.layout.tab_picker_item, listView, false);
    //        TextView textView = (TextView) defaultView.findViewById(R.id.title);
    //      textView.setText(musicName);
    //        listView.addHeaderView(defaultView, null, true);
    //        mStaticItemCount++;

}

From source file:org.mariotaku.twidere.util.DataStoreUtils.java

public static void deleteStatus(@NonNull ContentResolver cr, @NonNull UserKey accountKey,
        @NonNull String statusId, @Nullable ParcelableStatus status) {

    final String host = accountKey.getHost();
    final String deleteWhere, updateWhere;
    final String[] deleteWhereArgs, updateWhereArgs;
    if (host != null) {
        deleteWhere = Expression/*from   ww  w  . ja v a 2  s.  com*/
                .and(Expression.likeRaw(new Column(Statuses.ACCOUNT_KEY), "'%@'||?"), Expression.or(
                        Expression.equalsArgs(Statuses.STATUS_ID), Expression.equalsArgs(Statuses.RETWEET_ID)))
                .getSQL();
        deleteWhereArgs = new String[] { host, statusId, statusId };
        updateWhere = Expression.and(Expression.likeRaw(new Column(Statuses.ACCOUNT_KEY), "'%@'||?"),
                Expression.equalsArgs(Statuses.MY_RETWEET_ID)).getSQL();
        updateWhereArgs = new String[] { host, statusId };
    } else {
        deleteWhere = Expression
                .or(Expression.equalsArgs(Statuses.STATUS_ID), Expression.equalsArgs(Statuses.RETWEET_ID))
                .getSQL();
        deleteWhereArgs = new String[] { statusId, statusId };
        updateWhere = Expression.equalsArgs(Statuses.MY_RETWEET_ID).getSQL();
        updateWhereArgs = new String[] { statusId };
    }
    for (final Uri uri : STATUSES_URIS) {
        cr.delete(uri, deleteWhere, deleteWhereArgs);
        if (status != null) {
            final ContentValues values = new ContentValues();
            values.putNull(Statuses.MY_RETWEET_ID);
            values.put(Statuses.RETWEET_COUNT, status.retweet_count - 1);
            cr.update(uri, values, updateWhere, updateWhereArgs);
        }
    }
}

From source file:com.bt.download.android.gui.Librarian.java

public void updateSharedStates(byte fileType, List<FileDescriptor> fds) {
    if (fds == null || fds.size() == 0) {
        return;/*from  w  w  w  .j a va2  s  .  co  m*/
    }

    try {
        ContentResolver cr = context.getContentResolver();

        Set<Integer> sharedFiles = getSharedFiles(fds.get(0).fileType);

        int size = fds.size();

        // we know this is a slow process, we can improve it later
        for (int i = 0; i < size; i++) {

            FileDescriptor fileDescriptor = fds.get(i);

            ContentValues contentValues = new ContentValues();
            contentValues.put(SharingColumns.SHARED, fileDescriptor.shared ? 1 : 0);

            // Is this a NEW Shared File?
            if (!sharedFiles.contains(fileDescriptor.id) && fileDescriptor.shared) {
                // insert in table as unshared.
                contentValues.put(SharingColumns.FILE_ID, fileDescriptor.id);
                contentValues.put(SharingColumns.FILE_TYPE, fileType);
                cr.insert(Sharing.Media.CONTENT_URI, contentValues);
            } else {
                // everything else is an update
                cr.update(Sharing.Media.CONTENT_URI, contentValues,
                        SharingColumns.FILE_ID + "=? AND " + SharingColumns.FILE_TYPE + "=?",
                        new String[] { String.valueOf(fileDescriptor.id), String.valueOf(fileType) });
            }
        }

        invalidateCountCache(fileType);

    } catch (Throwable e) {
        Log.e(TAG, "Failed to update share states", e);
    }
}

From source file:de.vanita5.twittnuker.task.CacheUsersStatusesTask.java

@Override
protected Void doInBackground(final Void... args) {
    if (responses == null || responses.length == 0)
        return null;
    final ContentResolver resolver = context.getContentResolver();
    final Extractor extractor = new Extractor();
    final Set<ContentValues> usersValues = new HashSet<>();
    final Set<ContentValues> statusesValues = new HashSet<>();
    final Set<ContentValues> hashTagValues = new HashSet<>();
    final Set<Long> allStatusIds = new HashSet<>();
    final Set<String> allHashTags = new HashSet<>();
    final Set<User> users = new HashSet<>();

    for (final TwitterListResponse<twitter4j.Status> response : responses) {
        if (response == null || response.list == null) {
            continue;
        }//from   w  w w . j  ava  2s  . c  o  m
        final List<twitter4j.Status> list = response.list;
        final Set<Long> userIds = new HashSet<>();
        for (final twitter4j.Status status : list) {
            if (status == null || status.getId() <= 0) {
                continue;
            }
            if (status.isRetweet()) {
                final User retweetUser = status.getRetweetedStatus().getUser();
                userIds.add(retweetUser.getId());
            }
            allStatusIds.add(status.getId());
            statusesValues.add(createStatus(status, response.account_id));
            allHashTags.addAll(extractor.extractHashtags(status.getText()));
            final User user = status.getUser();
            users.add(user);
            userIds.add(user.getId());
            final ContentValues filtered_users_values = new ContentValues();
            filtered_users_values.put(Filters.Users.NAME, user.getName());
            filtered_users_values.put(Filters.Users.SCREEN_NAME, user.getScreenName());
            final String filtered_users_where = Expression.equals(Filters.Users.USER_ID, user.getId()).getSQL();
            resolver.update(Filters.Users.CONTENT_URI, filtered_users_values, filtered_users_where, null);
        }
    }

    bulkDelete(resolver, CachedStatuses.CONTENT_URI, CachedStatuses.STATUS_ID, allStatusIds, null, false);
    bulkInsert(resolver, CachedStatuses.CONTENT_URI, statusesValues);

    for (final String hashtag : allHashTags) {
        final ContentValues values = new ContentValues();
        values.put(CachedHashtags.NAME, hashtag);
        hashTagValues.add(values);
    }
    bulkDelete(resolver, CachedHashtags.CONTENT_URI, CachedHashtags.NAME, allHashTags, null, true);
    bulkInsert(resolver, CachedHashtags.CONTENT_URI, hashTagValues);

    for (final User user : users) {
        usersValues.add(createCachedUser(user));
    }
    bulkInsert(resolver, CachedUsers.CONTENT_URI, usersValues);
    return null;
}

From source file:de.ub0r.android.callmeter.data.RuleMatcher.java

/**
 * Match a single log record.//from w  ww  .  j  a v  a 2  s.c o m
 *
 * @param cr  {@link ContentResolver}
 * @param lid id of log item
 * @param pid id of plan
 */
public static void matchLog(final ContentResolver cr, final long lid, final int pid) {
    if (cr == null) {
        Log.e(TAG, "matchLog(null, lid, pid)");
        return;
    }
    if (lid < 0L || pid < 0L) {
        Log.e(TAG, "matchLog(cr, " + lid + "," + pid + ")");
        return;
    }
    Log.d(TAG, "matchLog(cr, ", lid, ",", pid, ")");

    if (plans == null) {
        Log.e(TAG, "plans = null");
        return;
    }
    final Plan p = plans.get(pid);
    if (p == null) {
        Log.e(TAG, "plan=null");
        return;
    }
    final Cursor log = cr.query(DataProvider.Logs.CONTENT_URI, DataProvider.Logs.PROJECTION,
            DataProvider.Logs.ID + " = ?", new String[] { String.valueOf(lid) }, null);
    if (log == null) {
        return;
    }
    if (!log.moveToFirst()) {
        Log.e(TAG, "no log: " + log);
        log.close();
        return;
    }
    final int t = log.getInt(DataProvider.Logs.INDEX_TYPE);
    p.checkBillday(log);
    final ContentValues cv = new ContentValues();
    cv.put(DataProvider.Logs.PLAN_ID, pid);
    final float ba = p.getBilledAmount(log);
    cv.put(DataProvider.Logs.BILL_AMOUNT, ba);
    final float bc = p.getCost(log, ba);
    cv.put(DataProvider.Logs.COST, bc);
    cv.put(DataProvider.Logs.FREE, p.getFree(log, bc));
    p.updatePlan(ba, bc, t);
    cr.update(DataProvider.Logs.CONTENT_URI, cv, DataProvider.Logs.ID + " = ?",
            new String[] { String.valueOf(lid) });
    log.close();
}