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:org.kontalk.data.Contact.java

public static String numberByUserId(Context context, String userId) {
    Cursor c = null;/*from ww  w.  jav  a  2s .com*/
    try {
        ContentResolver cres = context.getContentResolver();
        c = cres.query(Uri.withAppendedPath(Users.CONTENT_URI, userId), new String[] { Users.NUMBER }, null,
                null, null);

        if (c.moveToFirst())
            return c.getString(0);
    } finally {
        if (c != null)
            c.close();
    }

    return null;
}

From source file:cx.ring.model.CallContact.java

public void displayContact(Context context) {
    if (context == null) {
        Log.d(TAG, "displayContact: context is null");
        return;/*from w  w  w .ja  v a 2  s  .  c  o  m*/
    }

    if (getId() == UNKNOWN_ID) {
        Log.d(TAG, "displayContact: contact is unknown");
        displayAddContactConfirmationDialog(context);
    } else {
        Log.d(TAG, "displayContact: contact is known, displaying...");
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(getId()));
            intent.setData(uri);
            context.startActivity(intent);
        } catch (ActivityNotFoundException exc) {
            exc.printStackTrace();
        }
    }
}

From source file:edu.nd.darts.cimon.CimonListView.java

public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    if (DebugLog.DEBUG)
        Log.d(TAG, "CimonListView.onCreateLoader - id: " + id);
    if (id == 0) {
        /*         String[] projection = {MetricInfoTable.COLUMN_TITLE, 
                       MetricInfoTable.COLUMN_DESCRIPTION,
                       MetricInfoTable.COLUMN_POWER,
                       MetricInfoTable.COLUMN_SUPPORTED};*/
        CursorLoader cursorLoader = new CursorLoader(this,
                Uri.withAppendedPath(CimonContentProvider.CATEGORY_URI, String.valueOf(category)), null, null,
                null, MetricInfoTable.COLUMN_ID + " ASC");
        //         cursorLoader.setUpdateThrottle(250);
        return cursorLoader;
    } else {/*from  w  w w.  j  a v  a2 s.  c o m*/
        /*         String[] projection = {MetricsTable.COLUMN_ID, 
                       MetricsTable.COLUMN_METRIC,
                       MetricsTable.COLUMN_MAX,
                       MetricsTable.COLUMN_UNITS};*/
        CursorLoader cursorLoader = new CursorLoader(this,
                Uri.withAppendedPath(CimonContentProvider.GRP_METRICS_URI, String.valueOf(id)), null, null,
                null, MetricsTable.COLUMN_ID + " ASC");
        //         cursorLoader.setUpdateThrottle(250);
        return cursorLoader;
    }
}

From source file:com.securecomcode.text.contacts.ContactAccessor.java

/***
 * If the code below looks shitty to you, that's because it was taken
 * directly from the Android source, where shitty code is all you get.
 *///from  w w  w . ja  va2 s  .  co m

public Cursor getCursorForRecipientFilter(CharSequence constraint, ContentResolver mContentResolver) {
    final String SORT_ORDER = Contacts.TIMES_CONTACTED + " DESC," + Contacts.DISPLAY_NAME + ","
            + Contacts.Data.IS_SUPER_PRIMARY + " DESC," + Phone.TYPE;

    final String[] PROJECTION_PHONE = { Phone._ID, // 0
            Phone.CONTACT_ID, // 1
            Phone.TYPE, // 2
            Phone.NUMBER, // 3
            Phone.LABEL, // 4
            Phone.DISPLAY_NAME, // 5
    };

    String phone = "";
    String cons = null;

    if (constraint != null) {
        cons = constraint.toString();

        if (RecipientsAdapter.usefulAsDigits(cons)) {
            phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons);
            if (phone.equals(cons) && !PhoneNumberUtils.isWellFormedSmsAddress(phone)) {
                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.amaze.carbonfilemanager.utils.files.Futils.java

private static Uri fileToContentUri(Context context, String path, String volume) {
    String[] projection = null;/*from ww w.ja  v a 2s .  c  o m*/
    final String where = MediaStore.MediaColumns.DATA + " = ?";
    Uri baseUri = MediaStore.Files.getContentUri(volume);
    boolean isMimeTypeImage = false, isMimeTypeVideo = false, isMimeTypeAudio = false;
    isMimeTypeImage = Icons.isPicture(path);
    if (!isMimeTypeImage) {
        isMimeTypeVideo = Icons.isVideo(path);
        if (!isMimeTypeVideo) {
            isMimeTypeAudio = Icons.isVideo(path);
        }
    }
    if (isMimeTypeImage || isMimeTypeVideo || isMimeTypeAudio) {
        projection = new String[] { BaseColumns._ID };
        if (isMimeTypeImage) {
            baseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if (isMimeTypeVideo) {
            baseUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if (isMimeTypeAudio) {
            baseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
    } else {
        projection = new String[] { BaseColumns._ID, MediaStore.Files.FileColumns.MEDIA_TYPE };
    }
    ContentResolver cr = context.getContentResolver();
    Cursor c = cr.query(baseUri, projection, where, new String[] { path }, null);
    try {
        if (c != null && c.moveToNext()) {
            boolean isValid = false;
            if (isMimeTypeImage || isMimeTypeVideo || isMimeTypeAudio) {
                isValid = true;
            } else {
                int type = c.getInt(c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MEDIA_TYPE));
                isValid = type != 0;
            }

            if (isValid) {
                // Do not force to use content uri for no media files
                long id = c.getLong(c.getColumnIndexOrThrow(BaseColumns._ID));
                return Uri.withAppendedPath(baseUri, String.valueOf(id));
            }
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return null;
}

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

/**
 * Check that inserting a new model works as expected
 */// w  w  w .  j  a v  a2  s . c  om
public void testInsertAndUpdateModel() throws Exception {
    final ContentResolver cr = getContext().getContentResolver();
    ContentValues cv = new ContentValues();
    // Insert a new model
    cv.put(FlashCardsContract.Model.NAME, TEST_MODEL_NAME);
    cv.put(FlashCardsContract.Model.FIELD_NAMES, Utils.joinFields(TEST_MODEL_FIELDS));
    cv.put(FlashCardsContract.Model.NUM_CARDS, TEST_MODEL_CARDS.length);
    cv.put(FlashCardsContract.Model.CSS, TEST_MODEL_CSS);
    Uri modelUri = cr.insert(FlashCardsContract.Model.CONTENT_URI, cv);
    assertNotNull("Check inserted model isn't null", modelUri);
    long mid = Long.parseLong(modelUri.getLastPathSegment());
    final Collection col = CollectionHelper.getInstance().getCol(getContext());
    try {
        JSONObject model = col.getModels().get(mid);
        assertEquals("Check model name", TEST_MODEL_NAME, model.getString("name"));
        assertEquals("Check css", TEST_MODEL_CSS, model.getString("css"));
        assertEquals("Check templates length", TEST_MODEL_CARDS.length, model.getJSONArray("tmpls").length());
        assertEquals("Check field length", TEST_MODEL_FIELDS.length, model.getJSONArray("flds").length());
        JSONArray flds = model.getJSONArray("flds");
        for (int i = 0; i < flds.length(); i++) {
            assertEquals("Check name of fields", flds.getJSONObject(i).getString("name"), TEST_MODEL_FIELDS[i]);
        }
        // Update each of the templates in the model
        for (int i = 0; i < TEST_MODEL_CARDS.length; i++) {
            cv = new ContentValues();
            cv.put(FlashCardsContract.CardTemplate.NAME, TEST_MODEL_CARDS[i]);
            cv.put(FlashCardsContract.CardTemplate.QUESTION_FORMAT, TEST_MODEL_QFMT[i]);
            cv.put(FlashCardsContract.CardTemplate.ANSWER_FORMAT, TEST_MODEL_AFMT[i]);
            cv.put(FlashCardsContract.CardTemplate.BROWSER_QUESTION_FORMAT, TEST_MODEL_QFMT[i]);
            cv.put(FlashCardsContract.CardTemplate.BROWSER_ANSWER_FORMAT, TEST_MODEL_AFMT[i]);
            Uri tmplUri = Uri.withAppendedPath(Uri.withAppendedPath(modelUri, "templates"),
                    Integer.toString(i));
            assertTrue("Update rows", cr.update(tmplUri, cv, null, null) > 0);
            JSONObject template = col.getModels().get(mid).getJSONArray("tmpls").getJSONObject(i);
            assertEquals("Check template name", TEST_MODEL_CARDS[i], template.getString("name"));
            assertEquals("Check qfmt", TEST_MODEL_QFMT[i], template.getString("qfmt"));
            assertEquals("Check afmt", TEST_MODEL_AFMT[i], template.getString("afmt"));
            assertEquals("Check bqfmt", TEST_MODEL_QFMT[i], template.getString("bqfmt"));
            assertEquals("Check bafmt", TEST_MODEL_AFMT[i], template.getString("bafmt"));
        }
    } finally {
        // Delete the model (this will force a full-sync)
        try {
            col.modSchema(false);
            col.getModels().rem(col.getModels().get(mid));
        } catch (ConfirmModSchemaException e) {
            // This will never happen
            throw new IllegalStateException("Unexpected ConfirmModSchemaException trying to remove model");
        }
    }
}

From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java

@Override
protected void onPostExecute(Uri result) {
    BreadcrumbsTracks tracks = mService.getBreadcrumbsTracks();
    Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata");
    List<String> segments = result.getPathSegments();
    Integer bcTrackId = Integer.valueOf(segments.get(segments.size() - 2));

    ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>();

    metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId)));
    if (mDescription != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, mDescription));
    }//from  ww  w  .j  av  a  2s.c o  m
    if (mIsPublic != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, mIsPublic));
    }
    metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, mBundleId));
    metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, mActivityId));

    // Store in OGT provider
    ContentResolver resolver = mContext.getContentResolver();
    resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1]));

    // Store in Breadcrumbs adapter
    tracks.addSyncedTrack(Long.valueOf(mTrackUri.getLastPathSegment()), bcTrackId);
    if (mIsBundleCreated) {
        mService.getBreadcrumbsTracks().addBundle(Integer.parseInt(mBundleId), mBundleName, mBundleDescription);
    }
    //"http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx"
    mService.getBreadcrumbsTracks().addTrack(bcTrackId, mName, Integer.valueOf(mBundleId), mDescription, null,
            null, null, mIsPublic, null, null, null, null, null);

    super.onPostExecute(result);
}

From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ??/*from   w ww.ja v a 2s  .c  om*/
 *
 * @param messageType
 *            ?MMS,SMS,Email
 * @param folderType
 *            
 * @param index
 *            ?
 * @return ?
 */
private JSONObject getMessage(String messageType, String folderType, int index) throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    JSONObject message = new JSONObject();
    try {
        // ???
        String[] projection = new String[] { "_id", "subject", "address", "body", "date", "read" };
        folderType = folderType.toLowerCase();
        Uri uri = Uri.withAppendedPath(mSMSContentUri, folderType);
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(uri, projection, null, null, "date desc");

        if (null == cursor) {
            return message;
        }
        // ??
        if (!cursor.moveToPosition(index)) {
            cursor.close();
            return message;
        }
        // TODO:?SIM??
        message = getMessageFromCursor(cursor);
        cursor.close();

    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return message;
}

From source file:com.polyvi.xface.extension.XMessagingExt.java

/**
 * ??/*  w w w  . j a  v a2s.  c om*/
 * @param messageType       ?MMS,SMS,Email
 * @param  folderType       
 * @param  index            ?
 * @return                  ?
 */
private JSONObject getMessage(String messageType, String folderType, int index) throws JSONException {
    //TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    JSONObject message = new JSONObject();
    try {
        // ???
        String[] projection = new String[] { "_id", "subject", "address", "body", "date", "read" };
        folderType = folderType.toLowerCase();
        Uri uri = Uri.withAppendedPath(mSMSContentUri, folderType);
        ContentResolver resolver = getContext().getContentResolver();
        Cursor cursor = resolver.query(uri, projection, null, null, "date desc");

        if (null == cursor) {
            return message;
        }
        // ??
        if (!cursor.moveToPosition(index)) {
            cursor.close();
            return message;
        }
        //TODO:?SIM??
        message = getMessageFromCursor(cursor);
        cursor.close();

    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return message;
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

private void getServerPhotos(SyncContext context, String feedUrl, int maxDownloads, GDataSyncData syncData,
        SyncResult syncResult) {//w w  w . j  a  v  a  2 s .  co m
    final ContentResolver cr = getContext().getContentResolver();
    Cursor cursor = cr.query(Photos.CONTENT_URI,
            new String[] { Photos._SYNC_ID, Photos._SYNC_VERSION, Photos.PERSON_ID, Photos.DOWNLOAD_REQUIRED,
                    Photos._ID },
            "" + "_sync_account=? AND download_required != 0", new String[] { getAccount() }, null);
    try {
        int numFetched = 0;
        while (cursor.moveToNext()) {
            if (numFetched >= maxDownloads) {
                break;
            }
            String photoSyncId = cursor.getString(0);
            String photoVersion = cursor.getString(1);
            long person = cursor.getLong(2);
            String photoUrl = feedUrl + "/" + photoSyncId;
            long photoId = cursor.getLong(4);

            try {
                context.setStatusText("Downloading photo " + photoSyncId);
                ++numFetched;
                ++mPhotoDownloads;
                InputStream inputStream = mContactsClient.getMediaEntryAsStream(photoUrl, getAuthToken());
                savePhoto(person, inputStream, photoVersion);
                syncResult.stats.numUpdates++;
            } catch (IOException e) {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.d(TAG, "error downloading " + photoUrl, e);
                }
                syncResult.stats.numIoExceptions++;
                return;
            } catch (HttpException e) {
                switch (e.getStatusCode()) {
                case HttpException.SC_UNAUTHORIZED:
                    if (Config.LOGD) {
                        Log.d(TAG, "not authorized to download " + photoUrl, e);
                    }
                    syncResult.stats.numAuthExceptions++;
                    return;
                case HttpException.SC_FORBIDDEN:
                case HttpException.SC_NOT_FOUND:
                    final String exceptionMessage = e.getMessage();
                    if (Config.LOGD) {
                        Log.d(TAG, "unable to download photo " + photoUrl + ", " + exceptionMessage
                                + ", ignoring");
                    }
                    ContentValues values = new ContentValues();
                    values.put(Photos.SYNC_ERROR, exceptionMessage);
                    Uri photoUri = Uri.withAppendedPath(ContentUris.withAppendedId(People.CONTENT_URI, photoId),
                            Photos.CONTENT_DIRECTORY);
                    cr.update(photoUri, values, null /* where */, null /* where args */);
                    break;
                default:
                    if (Config.LOGD) {
                        Log.d(TAG, "error downloading " + photoUrl, e);
                    }
                    syncResult.stats.numIoExceptions++;
                    return;
                }
            }
        }
        final boolean hasMoreToSync = numFetched < cursor.getCount();
        GDataSyncData.FeedData feedData = new GDataSyncData.FeedData(0 /* no update time */, numFetched,
                hasMoreToSync, null /* no lastId */, 0 /* no feed index */);
        syncData.feedData.put(feedUrl, feedData);
    } finally {
        cursor.close();
    }
}