Example usage for android.net Uri withAppendedPath

List of usage examples for android.net Uri withAppendedPath

Introduction

In this page you can find the example usage for android.net Uri withAppendedPath.

Prototype

public static Uri withAppendedPath(Uri baseUri, String pathSegment) 

Source Link

Document

Creates a new Uri by appending an already-encoded path segment to a base Uri.

Usage

From source file:com.gsma.rcs.ri.utils.RcsContactUtil.java

private String getDisplayNameFromAddressBook(ContactId contact) {
    /* First try to get it from cache */
    String displayName = mDisplayNameAndroidCache.get(contact);
    if (displayName != null) {
        return displayName;
    }//from   w ww.  j  a v a  2s  .c o m
    /* Not found in cache: query the Android address book */
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(contact.toString()));
    Cursor cursor = null;
    try {
        cursor = mResolver.query(uri, PROJ_DISPLAY_NAME, null, null, null);
        if (cursor == null) {
            throw new SQLException("Cannot query display name for contact=" + contact);
        }
        if (!cursor.moveToFirst()) {
            return null;
        }
        displayName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
        /* Insert in cache */
        mDisplayNameAndroidCache.put(contact, displayName);
        return displayName;

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.renard.documentview.DocumentTextFragment.java

void saveIfTextHasChanged() {
    if (mHasTextChanged) {
        mHasTextChanged = false;/*from   w  w w .  j a  va2  s.c  om*/
        final Uri uri = Uri.withAppendedPath(DocumentContentProvider.CONTENT_URI, String.valueOf(mDocumentId));
        List<Uri> ids = new ArrayList<>();
        List<Spanned> texts = new ArrayList<>();
        ids.add(uri);
        texts.add(mEditText.getText());
        saveTask = new BaseDocumentActivitiy.SaveDocumentTask(getActivity(), ids, texts);
        saveTask.execute();
    }
}

From source file:org.thoughtcrime.securesms.contacts.ContactAccessorNewApi.java

@Override
public Cursor getCursorForRecipientFilter(CharSequence constraint, ContentResolver mContentResolver) {
    String phone = "";
    String cons = null;/*  w ww . j  a  v  a 2  s .  co  m*/
    if (constraint != null) {
        cons = constraint.toString();

        if (RecipientsAdapter.usefulAsDigits(cons)) {
            phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons);
            if (phone.equals(cons)) {
                phone = "";
            } else {
                phone = phone.trim();
            }
        }
    }

    Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons));
    String selection = String.format("%s=%s OR %s=%s OR %s=%s", Phone.TYPE, Phone.TYPE_MOBILE, Phone.TYPE,
            Phone.TYPE_WORK_MOBILE, Phone.TYPE, Phone.TYPE_MMS);

    Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, null, null, SORT_ORDER);

    if (phone.length() > 0) {
        ArrayList result = new ArrayList();
        result.add(Integer.valueOf(-1)); // ID
        result.add(Long.valueOf(-1)); // CONTACT_ID
        result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE
        result.add(phone); // NUMBER

        /*
         * The "\u00A0" keeps Phone.getDisplayLabel() from deciding
         * to display the default label ("Home") next to the transformation
         * of the letters into numbers.
         */
        result.add("\u00A0"); // LABEL
        result.add(cons); // NAME

        ArrayList<ArrayList> wrap = new ArrayList<ArrayList>();
        wrap.add(result);

        ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap);

        return new MergeCursor(new Cursor[] { translated, phoneCursor });
    } else {
        return phoneCursor;
    }

}

From source file:com.nononsenseapps.feeder.model.RssSyncHelper.java

/**
 * Synchronize pending updates/*from w  ww .  j av a2s.co  m*/
 *
 * @param context
 * @param operations deletes will be added to operations
 */
public static void syncPending(final Context context, final String token,
        final ArrayList<ContentProviderOperation> operations) {
    if (token == null) {
        throw new NullPointerException("Token was null");
    }

    Cursor c = null;
    try {
        c = context.getContentResolver().query(PendingNetworkSQL.URI, PendingNetworkSQL.FIELDS, null, null,
                null);

        while (c != null && c.moveToNext()) {
            PendingNetworkSQL pending = new PendingNetworkSQL(c);
            boolean success = false;

            if (pending.isDelete()) {
                try {
                    // catch 404 special
                    deleteFeed(context, token, pending.url);
                    success = true;
                } catch (RetrofitError e) {
                    if (e.getResponse() != null && e.getResponse().getStatus() == 404) {
                        // 404 is fine, already deleted
                        success = true;
                    } else {
                        // Not OK, throw it
                        throw e;
                    }

                }
            } else if (pending.isPut()) {
                putFeed(context, token, pending.title, pending.url, pending.tag);
                success = true;
            }

            if (success) {
                // Remove from db
                operations.add(ContentProviderOperation
                        .newDelete(Uri.withAppendedPath(PendingNetworkSQL.URI, Long.toString(pending.id)))
                        .build());
            }
        }

    } finally {
        if (c != null) {
            c.close();
        }
    }
}

From source file:com.fede.Utilities.GeneralUtils.java

public static String getNameFromNumber(String number, Context c) throws NameNotFoundException {
    String name;/*w  w w. j  a  v  a  2 s .  co  m*/
    String[] columns = { ContactsContract.PhoneLookup.DISPLAY_NAME };

    Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, number);
    Cursor idCursor = c.getContentResolver().query(lookupUri, columns, null, null, null);
    if (idCursor.moveToFirst()) {
        int nameIdx = idCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME);
        name = idCursor.getString(nameIdx);
    } else {
        throw new NameNotFoundException(number);
    }
    idCursor.close();
    return name;
}

From source file:org.coocood.vcontentprovider.VContentProvider.java

private static ContentProviderOperation getOperation(Uri baseUri, JSONObject json, String table)
        throws JSONException {
    Uri uri = Uri.withAppendedPath(baseUri, table);
    ArrayList<String> columns = tableMap.get(table);
    ContentValues values = new ContentValues();
    for (int i = 0; i < columns.size(); i++) {
        String column = columns.get(i);
        if (json.has(column)) {
            String value = json.getString(column);

            // The id column index in the columns ArrayList is 0.
            // Put "_id" as the local id column name.
            values.put(i == 0 ? "_id" : column, value);
        }//w  w w .  j av  a2 s .co  m
    }
    return ContentProviderOperation.newUpdate(uri).withValues(values).build();
}

From source file:org.opendatakit.provider.FormsProviderUtils.java

/**
 * @param appName required./*from  w ww .j  a v  a 2s  .c  o m*/
 * @param tableId required.
 * @param formId  may be null. If null, screenPath and elementKeyToStringifiedValue must be null
 * @param instanceId may be null.
 * @param screenPath may be null.
 * @param elementKeyToValueMap may be null or empty. Contents are elementKey -to-
 *                                        value for that elementKey. Used to
 *                                        initialized field values and session variables.
 * @return URI for this survey and its arguments.
 */
public static String constructSurveyUri(String appName, String tableId, String formId, String instanceId,
        String screenPath, Map<String, Object> elementKeyToValueMap) {
    if (tableId == null) {
        WebLogger.getLogger(appName).e(TAG, "constructSurveyUri: tableId cannot be null returning.");
        return null;
    }
    if (formId == null && screenPath != null) {
        WebLogger.getLogger(appName).e(TAG,
                "constructSurveyUri: screenPath cannot be " + "specified if formId is null. returning.");
        return null;
    }
    if (formId == null && elementKeyToValueMap != null && !elementKeyToValueMap.isEmpty()) {
        WebLogger.getLogger(appName).e(TAG,
                "constructSurveyUri: jsonMap cannot be " + "specified if formId is null. returning.");
        return null;
    }

    // if no formId is specified, let ODK Survey choose the default form to use on this tableId.
    if (formId == null) {
        formId = "_";
    }

    Uri uri = Uri.withAppendedPath(
            Uri.withAppendedPath(Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), tableId), formId);

    String uriStr = uri + "/" + "#";
    // Now we need to add our fragment parameters (client-side parsing).
    try {
        String continueStr = "";

        if (instanceId != null && !instanceId.isEmpty()) {
            uriStr += URI_SURVEY_QUERY_PARAM_INSTANCE_ID + "=" + encodeFragmentUnquotedStringValue(instanceId);
            continueStr = "&";
        }
        if (screenPath != null && !screenPath.isEmpty()) {
            uriStr += continueStr + URI_SURVEY_QUERY_PARAM_SCREEN_PATH + "="
                    + encodeFragmentUnquotedStringValue(screenPath);
            continueStr = "&";
        }
        if (elementKeyToValueMap != null && !elementKeyToValueMap.isEmpty()) {
            // We'll add all the entries to the URI as key-value pairs.
            // Use a StringBuilder in case we have a lot of these.
            // We'll assume we already have parameters added to the frame. This is
            // reasonable because this URI call thus far insists on an instanceId,
            // so
            // we know there will be at least that parameter.
            StringBuilder stringBuilder = new StringBuilder(uriStr);
            for (Map.Entry<String, Object> objEntry : elementKeyToValueMap.entrySet()) {
                // First add the ampersand
                stringBuilder.append(continueStr);
                continueStr = "&";
                stringBuilder.append(encodeFragmentUnquotedStringValue(objEntry.getKey()));
                stringBuilder.append("=");
                // JSON stringify the value then URL encode it.
                // We've got to replace the plus with %20, which is what js's
                // decodeURIComponent expects.
                String escapedValue = encodeFragmentObjectValue(objEntry.getValue());
                stringBuilder.append(escapedValue);
            }
            uriStr = stringBuilder.toString();
        }
    } catch (UnsupportedEncodingException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        throw new IllegalArgumentException("error escaping URI parameters");
    } catch (JsonProcessingException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        throw new IllegalArgumentException("error escaping elementKeyToValueMap parameter");
    }
    WebLogger.getLogger(appName).d(TAG, "constructSurveyUri: " + uriStr);
    return uriStr;
}

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 w  w.  j a  va 2  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:org.jamienicol.episodes.EpisodeDetailsFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    final int episodeId = args.getInt("episodeId");
    final Uri uri = Uri.withAppendedPath(ShowsProvider.CONTENT_URI_EPISODES, String.valueOf(episodeId));
    final String[] projection = { EpisodesTable.COLUMN_NAME, EpisodesTable.COLUMN_OVERVIEW,
            EpisodesTable.COLUMN_SEASON_NUMBER, EpisodesTable.COLUMN_EPISODE_NUMBER,
            EpisodesTable.COLUMN_FIRST_AIRED, EpisodesTable.COLUMN_WATCHED };
    return new CursorLoader(getActivity(), uri, projection, null, null, null);
}

From source file:com.kylebeal.datedialogfragment.example.DateDetailFragment.java

private void setDbDate(Calendar newDate) {
    //get activity's content resolver and update
    Uri updateUri = Uri.withAppendedPath(Uri.parse("content://" + DatesProvider.AUTHORITY + "/dates"),
            String.valueOf(mDateId));
    ContentValues newDateValues = new ContentValues();
    newDateValues.put("date", DatesDbHelper.SHORT_DATE_FORMAT.format(newDate.getTime()));
    getActivity().getContentResolver().update(updateUri, newDateValues, "_id=?",
            new String[] { String.valueOf(mDateId) });
}