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.abcvoipsip.ui.account.AccountsEditListFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Use custom drag and drop view
    View v = inflater.inflate(R.layout.accounts_edit_list, container, false);

    DragnDropListView lv = (DragnDropListView) v.findViewById(android.R.id.list);
    lv.setGrabberId(R.id.grabber);//from   w w  w. ja  v  a2s .  co  m
    // Setup the drop listener
    lv.setOnDropListener(new DropListener() {
        @Override
        public void drop(int from, int to) {
            Log.d(THIS_FILE, "Drop from " + from + " to " + to);
            int i;
            // First of all, compute what we get before move
            ArrayList<Long> orderedList = new ArrayList<Long>();
            CursorAdapter ad = (CursorAdapter) getListAdapter();
            for (i = 0; i < ad.getCount(); i++) {
                orderedList.add(ad.getItemId(i));
            }
            // Then, invert in the current list the two items ids
            Long moved = orderedList.remove(from);
            orderedList.add(to, moved);

            // Finally save that in db
            ContentResolver cr = getActivity().getContentResolver();
            for (i = 0; i < orderedList.size(); i++) {
                Uri uri = ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, orderedList.get(i));
                ContentValues cv = new ContentValues();
                cv.put(SipProfile.FIELD_PRIORITY, i);
                cr.update(uri, cv, null, null);
            }
        }
    });

    return v;
}

From source file:org.mozilla.gecko.db.LocalURLMetadata.java

/**
 * Saves a HashMap of metadata into the database. Will iterate through columns
 * in the Database and only save rows with matching keys in the HashMap.
 * Must not be called from UI or Gecko threads.
 */// w w w .j a  va2  s.co  m
@Override
public void save(final ContentResolver cr, final String url, final Map<String, Object> data) {
    ThreadUtils.assertNotOnUiThread();
    ThreadUtils.assertNotOnGeckoThread();

    try {
        ContentValues values = new ContentValues();

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

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

        Uri uri = uriWithProfile.buildUpon()
                .appendQueryParameter(BrowserContract.PARAM_INSERT_IF_NEEDED, "true").build();
        cr.update(uri, values, URLMetadataTable.URL_COLUMN + "=?",
                new String[] { (String) data.get(URLMetadataTable.URL_COLUMN) });
    } catch (Exception ex) {
        Log.e(LOGTAG, "error saving", ex);
    }
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * @param context The {@link Context} to use
 * @param id The song ID./*from   w  w  w.  j  a  v  a  2s  . co  m*/
 */
public static void setRingtone(final Context context, final long id) {
    final ContentResolver resolver = context.getContentResolver();
    final Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
    try {
        final ContentValues values = new ContentValues(2);
        values.put(AudioColumns.IS_RINGTONE, "1");
        values.put(AudioColumns.IS_ALARM, "1");
        resolver.update(uri, values, null, null);
    } catch (final UnsupportedOperationException ignored) {
        return;
    }

    final String[] projection = new String[] { BaseColumns._ID, MediaColumns.DATA, MediaColumns.TITLE };

    final String selection = BaseColumns._ID + "=" + id;
    Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection, null,
            null);
    try {
        if (cursor != null && cursor.getCount() == 1) {
            cursor.moveToFirst();
            RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, uri);
            final String message = context.getString(R.string.set_as_ringtone, cursor.getString(2));
            AppMsg.makeText(context, message, AppMsg.STYLE_CONFIRM).show();
        }
    } catch (Throwable ignored) {
        UIUtils.showLongMessage(context, R.string.ringtone_not_set);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:net.etuldan.sparss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from   w  w  w. j  a  v a 2s. c om

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            isChecked = !item.isChecked();
            item.setChecked(isChecked);
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPreferFullText = true;
                            mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                        }
                    });
                } else if (!isRefreshing()) {
                    ConnectivityManager connectivityManager = (ConnectivityManager) activity
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    // since we have acquired the networkInfo, we use it for basic checks
                    if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                        activity.startService(new Intent(activity, FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showSwipeProgress();
                            }
                        });
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.frostwire.android.gui.Librarian.java

public String renameFile(final Context context, FileDescriptor fd, String newFileName) {
    try {//from ww w .  j a v a 2  s.c  o  m
        String filePath = fd.filePath;
        File oldFile = new File(filePath);
        String ext = FilenameUtils.getExtension(filePath);
        File newFile = new File(oldFile.getParentFile(), newFileName + '.' + ext);
        ContentResolver cr = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaColumns.DATA, newFile.getAbsolutePath());
        values.put(MediaColumns.DISPLAY_NAME, FilenameUtils.getBaseName(newFileName));
        values.put(MediaColumns.TITLE, FilenameUtils.getBaseName(newFileName));
        TableFetcher fetcher = TableFetchers.getFetcher(fd.fileType);
        cr.update(fetcher.getContentUri(), values, BaseColumns._ID + "=?",
                new String[] { String.valueOf(fd.id) });
        oldFile.renameTo(newFile);
        return newFile.getAbsolutePath();
    } catch (Throwable e) {
        Log.e(TAG, "Failed to rename file: " + fd, e);
    }
    return null;
}

From source file:org.ohmage.db.DbHelper.java

public int updateResponseLocation(String locationStatus, Location location) {
    ContentValues vals = new ContentValues();
    vals.put(Responses.RESPONSE_STATUS, Response.STATUS_STANDBY);
    vals.put(Responses.RESPONSE_LOCATION_STATUS, locationStatus);

    if (location != null) {
        vals.put(Responses.RESPONSE_LOCATION_LATITUDE, location.getLatitude());
        vals.put(Responses.RESPONSE_LOCATION_LONGITUDE, location.getLongitude());
        vals.put(Responses.RESPONSE_LOCATION_PROVIDER, location.getProvider());
        vals.put(Responses.RESPONSE_LOCATION_ACCURACY, location.getAccuracy());
        vals.put(Responses.RESPONSE_LOCATION_TIME, location.getTime());
    }//from  ww w  . java2s .  c  o m

    ContentResolver cr = mContext.getContentResolver();
    int count = cr.update(Responses.CONTENT_URI, vals,
            Responses.RESPONSE_LOCATION_STATUS + " =? AND " + Responses.RESPONSE_STATUS + " = "
                    + Response.STATUS_WAITING_FOR_LOCATION,
            new String[] { SurveyGeotagService.LOCATION_UNAVAILABLE });

    return count;
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Test changing the selected deck/*from   w ww .  j  ava  2 s  . c om*/
 */
public void testSetSelectedDeck() {
    long deckId = mTestDeckIds[0];
    ContentResolver cr = getContext().getContentResolver();
    Uri selectDeckUri = FlashCardsContract.Deck.CONTENT_SELECTED_URI;
    ContentValues values = new ContentValues();
    values.put(FlashCardsContract.Deck.DECK_ID, deckId);
    cr.update(selectDeckUri, values, null, null);

    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    assertEquals("Check that the selected deck has been correctly set", deckId, col.getDecks().selected());
}

From source file:org.wheelmap.android.activity.MainSinglePaneActivity.java

public void resetKategorieFilter() {
    Uri mUri = Support.CategoriesContent.CONTENT_URI;
    Cursor c = getContentResolver().query(mUri, Support.CategoriesContent.PROJECTION, null, null,
            Support.CategoriesContent.DEFAULT_SORT_ORDER);

    for (int i = 0; i < c.getCount(); i++) {
        c.moveToPosition(i);/*w w  w .ja  v  a  2 s .c  o m*/
        int catId = Support.CategoriesContent.getCategoryId(c);

        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues();
        values.put(Support.CategoriesContent.SELECTED, Support.CategoriesContent.SELECTED_YES);

        String whereClause = "( " + Support.CategoriesContent.CATEGORY_ID + " = ?)";
        String[] whereValues = new String[] { Integer.toString(catId) };
        resolver.update(mUri, values, whereClause, whereValues);
    }
    c.close();
}

From source file:net.news.inrss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;// www . jav a2s.c  om

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        Log.d(TAG, "run: manual call of displayEntry(), fullText=false");
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    Log.d(TAG, "onOptionsItemSelected: alreadyMobilized");
                    mPreferFullText = true;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "run: manual call of displayEntry(), fullText=true");
                            mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                        }
                    });
                } else if (!isRefreshing()) {
                    Log.d(TAG, "onOptionsItemSelected: about to load article...");
                    mPreferFullText = false;
                    ConnectivityManager connectivityManager = (ConnectivityManager) activity
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    // since we have acquired the networkInfo, we use it for basic checks
                    if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                        activity.startService(new Intent(activity, FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                        Log.d(TAG, "onOptionsItemSelected: cannot load article. no internet connection.");
                    }
                } else {
                    Log.d(TAG, "onOptionsItemSelected: refreshing already in progress");
                }
            }
            mShowFullContentItem.setChecked(mPreferFullText);
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:org.ohmage.db.DbHelper.java

/**
 * Updates the status for a given campaign
 * /*from w ww .j  av a  2  s.com*/
 * @param campaignUrn
 *            the campaign to update
 * @param status
 *            the status code the campaign should be set to
 * @return true if the operation succeeded, false otherwise
 */
public boolean updateCampaignStatus(String campaignUrn, int status) {
    ContentValues values = new ContentValues();
    ContentResolver cr = mContext.getContentResolver();
    values.put(Campaigns.CAMPAIGN_STATUS, status);
    return cr.update(Campaigns.CONTENT_URI, values, Campaigns.CAMPAIGN_URN + "='" + campaignUrn + "'",
            null) > 0;
}