Example usage for android.content ContentResolver insert

List of usage examples for android.content ContentResolver insert

Introduction

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

Prototype

public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values) 

Source Link

Document

Inserts a row into a table at the given URL.

Usage

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

public void onClickOk(View view) {
    // only in insert mode

    String url = mUrlEditText.getText().toString();
    ContentResolver cr = getContentResolver();

    if (!url.startsWith(Constants.HTTP) && !url.startsWith(Constants.HTTPS)) {
        url = Constants.HTTP + url;/*  ww w  . java  2 s  . co  m*/
    }

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

    if (cursor.moveToFirst()) {
        cursor.close();
        Crouton.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Style.INFO);
    } else {
        cursor.close();
        ContentValues values = new ContentValues();

        values.put(FeedColumns.URL, url);
        values.putNull(FeedColumns.ERROR);

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

        if (name.trim().length() > 0) {
            values.put(FeedColumns.NAME, name);
        }
        values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
        cr.insert(FeedColumns.CONTENT_URI, values);
        cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
    }

    setResult(RESULT_OK);
    finish();
}

From source file:cn.edu.nju.dapenti.activity.EditFeedActivity.java

public void onClickOk(View view) {
    // only in insert mode

    String url = mUrlEditText.getText().toString();
    ContentResolver cr = getContentResolver();

    if (!url.startsWith(Constants.HTTP) && !url.startsWith(Constants.HTTPS)) {
        url = Constants.HTTP + url;/*ww w  . j av a2s.  c  om*/
    }

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

    if (cursor.moveToFirst()) {
        cursor.close();
        Toast.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Toast.LENGTH_LONG).show();
    } else {
        cursor.close();
        ContentValues values = new ContentValues();

        values.put(FeedColumns.URL, url);
        values.putNull(FeedColumns.ERROR);

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

        if (name.trim().length() > 0) {
            values.put(FeedColumns.NAME, name);
        }
        values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
        cr.insert(FeedColumns.CONTENT_URI, values);
        cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
        cr.notifyChange(FeedColumns.GROUPED_FEEDS_CONTENT_URI, null);
    }

    setResult(RESULT_OK);
    finish();
}

From source file:com.android.leanlauncher.LauncherModel.java

/**
 * Add an item to the database in a specified container. Sets the container, screen, cellX and
 * cellY fields of the item. Also assigns an ID to the item.
 *//*  w  w w  .j  a v  a  2 s .co  m*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container, final int cellX,
        final int cellY, final boolean notify) {
    item.container = container;
    item.cellX = cellX;
    item.cellY = cellY;

    final ContentValues values = new ContentValues();
    final ContentResolver cr = context.getContentResolver();
    item.onAddToDatabase(context, values);

    item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
    values.put(LauncherSettings.Favorites._ID, item.id);
    item.updateValuesWithCoordinates(values, item.cellX, item.cellY);

    Runnable r = new Runnable() {
        public void run() {
            cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI
                    : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);

            // Lock on mBgLock *after* the db operation
            synchronized (sBgLock) {
                sBgItemsIdMap.put(item.id, item);
                switch (item.itemType) {
                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
                    if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
                        sBgWorkspaceItems.add(item);
                    } else {
                        // Adding an item to a folder that doesn't exist.
                        String msg = "adding item: " + item + " to a container that " + " doesn't exist";
                        Log.e(TAG, msg);
                    }
                    break;
                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
                    sBgAppWidgets.add((LauncherAppWidgetInfo) item);
                    break;
                }
            }
        }
    };
    runOnWorkerThread(r);
}

From source file:com.nextgis.ngm_clink_monitoring.fragments.ObjectStatusFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    File tempPhotoFile = new File(mTempPhotoPath);

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
        GISApplication app = (GISApplication) getActivity().getApplication();
        ContentResolver contentResolver = app.getContentResolver();
        String photoFileName = getPhotoFileName();

        try {/*from   www  . j a va2  s. c o  m*/
            BitmapUtil.writeLocationToExif(tempPhotoFile, app.getCurrentLocation(), 0);
        } catch (IOException e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        Uri allAttachesUri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName
                + "/" + mObjectId + "/attach");

        ContentValues values = new ContentValues();
        values.put(VectorLayer.ATTACH_DISPLAY_NAME, photoFileName);
        values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg");
        //values.put(VectorLayer.ATTACH_DESCRIPTION, photoFileName);

        Uri attachUri = null;
        try {
            attachUri = contentResolver.insert(allAttachesUri, values);

        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        if (null != attachUri) {

            try {
                int exifOrientation = BitmapUtil.getOrientationFromExif(tempPhotoFile);

                // resize and rotate
                Bitmap sourceBitmap = BitmapFactory.decodeFile(tempPhotoFile.getPath());
                Bitmap resizedBitmap = BitmapUtil.getResizedBitmap(sourceBitmap,
                        FoclConstants.PHOTO_MAX_SIZE_PX, FoclConstants.PHOTO_MAX_SIZE_PX);
                Bitmap rotatedBitmap = BitmapUtil.rotateBitmap(resizedBitmap, exifOrientation);

                // jpeg compress
                File tempAttachFile = File.createTempFile("attach", null, app.getCacheDir());
                OutputStream tempOutStream = new FileOutputStream(tempAttachFile);
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, FoclConstants.PHOTO_JPEG_COMPRESS_QUALITY,
                        tempOutStream);
                tempOutStream.close();

                int newHeight = rotatedBitmap.getHeight();
                int newWidth = rotatedBitmap.getWidth();

                rotatedBitmap.recycle();

                // write EXIF to new file
                BitmapUtil.copyExifData(tempPhotoFile, tempAttachFile);

                ExifInterface attachExif = new ExifInterface(tempAttachFile.getCanonicalPath());

                attachExif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + ExifInterface.ORIENTATION_NORMAL);
                attachExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, "" + newHeight);
                attachExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, "" + newWidth);

                attachExif.saveAttributes();

                // attach data from tempAttachFile
                OutputStream attachOutStream = contentResolver.openOutputStream(attachUri);
                FoclFileUtil.copy(new FileInputStream(tempAttachFile), attachOutStream);
                attachOutStream.close();

                tempAttachFile.delete();

            } catch (IOException e) {
                Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }

            Log.d(TAG, attachUri.toString());

        } else {
            Log.d(TAG, "insert attach failed");
        }

        try {
            if (app.isOriginalPhotoSaving()) {
                File origPhotoFile = new File(getDailyPhotoFolder(), photoFileName);

                if (!com.nextgis.maplib.util.FileUtil.move(tempPhotoFile, origPhotoFile)) {
                    Toast.makeText(getActivity(), "Save original photo failed", Toast.LENGTH_LONG).show();
                }

            } else {
                tempPhotoFile.delete();
            }

            setPhotoGalleryAdapter();
            setPhotoGalleryVisibility(true);

        } catch (IOException e) {
            Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    }

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_CANCELED) {
        tempPhotoFile.delete();
    }
}

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

public void onClickOk(View view) {
    // only in insert mode

    String url = mUrlEditText.getText().toString();
    ContentResolver cr = getContentResolver();

    if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) {
        url = Constants.HTTP_SCHEME + url;
    }//from w ww  .  j  a  va2s .c om

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

    if (cursor.moveToFirst()) {
        cursor.close();
        Toast.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Toast.LENGTH_LONG).show();
    } else {
        cursor.close();
        ContentValues values = new ContentValues();

        values.put(FeedColumns.URL, url);
        values.putNull(FeedColumns.ERROR);

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

        if (name.trim().length() > 0) {
            values.put(FeedColumns.NAME, name);
        }
        values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
        cr.insert(FeedColumns.CONTENT_URI, values);
    }

    setResult(RESULT_OK);
    finish();
}

From source file:com.jackie.sunshine.app.sync.SunshineSyncAdapter.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName        A human-readable city name, e.g "Mountain View"
 * @param lat             the latitude of the city
 * @param lon             the longitude of the city
 * @return the row ID of the added location.
 */// w  w w  .j  a  v a 2s . com
private long addLocation(String locationSetting, String cityName, double lat, double lon) {
    ContentResolver locationResolver = getContext().getContentResolver();
    Cursor locationCursor = locationResolver.query(LocationEntry.CONTENT_URI,
            new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
            new String[] { locationSetting }, null);
    long locationId;
    // Students: First, check if the location with this city name exists in the db
    if (locationCursor != null && locationCursor.moveToFirst()) {
        // If it exists, return the current ID
        locationId = locationCursor.getLong(locationCursor.getColumnIndex(LocationEntry._ID));
    } else {
        // Otherwise, insert it using the content resolver and the base URI
        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon);
        Uri insertUri = locationResolver.insert(LocationEntry.CONTENT_URI, locationValues);
        locationId = ContentUris.parseId(insertUri);
    }

    if (locationCursor != null && !locationCursor.isClosed()) {
        locationCursor.close();
    }

    return locationId;
}

From source file:cn.edu.wyu.documentviewer.DocumentsActivity.java

private void saveStackBlocking() {
    final ContentResolver resolver = getContentResolver();
    final ContentValues values = new ContentValues();

    final byte[] rawStack = DurableUtils.writeToArrayOrNull(mState.stack);
    if (mState.action == ACTION_CREATE) {
        // Remember stack for last create
        values.clear();/*from  w  w  w. j  a va 2 s. co  m*/
        values.put(RecentColumns.KEY, mState.stack.buildKey());
        values.put(RecentColumns.STACK, rawStack);
        resolver.insert(RecentsProvider.buildRecent(), values);
    }

    // Remember location for next app launch
    final String packageName = getCallingPackageMaybeExtra();
    values.clear();
    values.put(ResumeColumns.STACK, rawStack);
    values.put(ResumeColumns.EXTERNAL, 0);
    resolver.insert(RecentsProvider.buildResume(packageName), values);
}

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.
 *//*from  w ww.  ja v  a2  s .  co 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.dwdesign.tweetings.fragment.UserListDetailsFragment.java

@Override
public boolean onMenuItemClick(final MenuItem item) {
    switch (item.getItemId()) {
    case MENU_FOLLOW: {
        if (mAccountId != mUserId) {
            if (mUserList.isFollowing()) {
                mService.destroyUserListSubscription(mAccountId, mUserList.getId());
            } else {
                mService.createUserListSubscription(mAccountId, mUserList.getId());
            }// w  ww .ja v  a2  s . co  m
        }
        break;
    }
    case MENU_ADD: {
        final Bundle args = new Bundle();
        args.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        args.putString(INTENT_KEY_TEXT, "");
        args.putInt(INTENT_KEY_LIST_ID, mUserList.getId());
        mAddMemberDialogFragment.setArguments(args);
        mAddMemberDialogFragment.show(getFragmentManager(), "add_member");
        break;
    }
    case MENU_ADD_TAB: {
        CustomTabsAdapter mAdapter;
        mAdapter = new CustomTabsAdapter(getActivity());
        ContentResolver mResolver;
        mResolver = getContentResolver();
        final String tabName = mListName;
        final String tabType = AUTHORITY_LIST_TIMELINE;
        final String tabIcon = "list";
        final long account_id = mAccountId;
        final String tabScreenName = mUserScreenName;
        final String tabListName = mListName;
        final String tabArguments = "{\"account_id\":" + account_id + ",\"screen_name\":\"" + tabScreenName
                + "\",\"list_name\":" + JSONObject.quote(tabListName) + "}";
        final ContentValues values = new ContentValues();
        values.put(Tabs.ARGUMENTS, tabArguments);
        values.put(Tabs.NAME, tabName);
        values.put(Tabs.POSITION, mAdapter.getCount());
        values.put(Tabs.TYPE, tabType);
        values.put(Tabs.ICON, tabIcon);
        mResolver.insert(Tabs.CONTENT_URI, values);
        Toast.makeText(this.getActivity(), R.string.list_tab_added, Toast.LENGTH_SHORT).show();
        break;
    }
    case MENU_DELETE: {
        if (mUserId != mAccountId)
            return false;
        mService.destroyUserList(mAccountId, mUserListId);
        break;
    }
    case MENU_EXTENSIONS: {
        final Intent intent = new Intent(INTENT_ACTION_EXTENSION_OPEN_USER_LIST);
        final Bundle extras = new Bundle();
        extras.putParcelable(INTENT_KEY_USER_LIST, new ParcelableUserList(mUserList, mAccountId));
        intent.putExtras(extras);
        startActivity(Intent.createChooser(intent, getString(R.string.open_with_extensions)));
        break;
    }
    }
    return true;
}

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  ava2  s.c  om*/
    }

    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);
    }
}