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.visva.voicerecorder.view.fragments.FragmentContact.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // If this is the loader for finding contacts in the Contacts Provider
    // (the only one supported)
    if (id == ContactsQuery.QUERY_ID) {
        Uri contentUri;//from  ww  w.  j a  va  2 s  . c  o  m

        // There are two types of searches, one which displays all contacts and
        // one which filters contacts by a search query. If mSearchTerm is set
        // then a search query has been entered and the latter should be used.

        if (mSearchTerm == null) {
            // Since there's no search string, use the content URI that searches the entire
            // Contacts table
            contentUri = ContactsQuery.CONTENT_URI;
        } else {
            // Since there's a search string, use the special content Uri that searches the
            // Contacts table. The URI consists of a base Uri and the search string.
            contentUri = Uri.withAppendedPath(ContactsQuery.FILTER_URI, Uri.encode(mSearchTerm));
        }

        // Returns a new CursorLoader for querying the Contacts table. No arguments are used
        // for the selection clause. The search string is either encoded onto the content URI,
        // or no contacts search string is used. The other search criteria are constants. See
        // the ContactsQuery interface.
        return new CursorLoader(getActivity(), contentUri, ContactsQuery.PROJECTION, ContactsQuery.SELECTION,
                null, ContactsQuery.SORT_ORDER);
    }
    return null;
}

From source file:com.zegoggles.smssync.CursorToMessage.java

private Message messageFromMapMms(Map<String, String> msgMap) throws MessagingException {
    if (LOCAL_LOGV)
        Log.v(TAG, "messageFromMapMms(" + msgMap + ")");

    final Uri msgRef = Uri.withAppendedPath(ServiceBase.MMS_PROVIDER, msgMap.get(MmsConsts.ID));
    Cursor curAddr = mContext.getContentResolver().query(Uri.withAppendedPath(msgRef, "addr"), null, null, null,
            null);/*from www  .ja  v a 2 s  . c o m*/

    // TODO: this is probably not the best way to determine if a message is inbound or outbound
    boolean inbound = true;
    final List<String> recipients = new ArrayList<String>(); // MMS recipients
    while (curAddr != null && curAddr.moveToNext()) {
        final String address = curAddr.getString(curAddr.getColumnIndex("address"));
        //final int type       = curAddr.getInt(curAddr.getColumnIndex("type"));

        if (MmsConsts.INSERT_ADDRESS_TOKEN.equals(address)) {
            inbound = false;
        } else {
            recipients.add(address);
        }
    }
    if (curAddr != null)
        curAddr.close();
    if (recipients.isEmpty()) {
        Log.w(TAG, "no recipients found");
        return null;
    }

    final String address = recipients.get(0);
    final PersonRecord[] records = new PersonRecord[recipients.size()];
    final Address[] addresses = new Address[recipients.size()];
    for (int i = 0; i < recipients.size(); i++) {
        records[i] = lookupPerson(recipients.get(i));
        addresses[i] = records[i].getAddress();
    }

    boolean backup = false;
    for (PersonRecord r : records) {
        if (backupPerson(r, DataType.MMS)) {
            backup = true;
            break;
        }
    }
    if (!backup)
        return null;

    final Message msg = new MimeMessage();
    msg.setSubject(getSubject(DataType.MMS, records[0]));
    final int msg_box = Integer.parseInt(msgMap.get("msg_box"));
    if (inbound) {
        // msg_box == MmsConsts.MESSAGE_BOX_INBOX does not work
        msg.setFrom(records[0].getAddress());
        msg.setRecipient(RecipientType.TO, mUserAddress);
    } else {
        msg.setRecipients(RecipientType.TO, addresses);
        msg.setFrom(mUserAddress);
    }

    try {
        Date then = new Date(1000 * Long.valueOf(msgMap.get(MmsConsts.DATE)));
        msg.setSentDate(then);
        msg.setInternalDate(then);
        msg.setHeader("Message-ID", createMessageId(then, address, msg_box));
    } catch (NumberFormatException n) {
        Log.e(TAG, "error parsing date", n);
    }

    // Threading by person ID, not by thread ID. I think this value is more stable.
    msg.setHeader("References",
            String.format(REFERENCE_UID_TEMPLATE, mReferenceValue, sanitize(records[0].getId())));
    msg.setHeader(Headers.ID, msgMap.get(MmsConsts.ID));
    msg.setHeader(Headers.ADDRESS, sanitize(address));
    msg.setHeader(Headers.DATATYPE, DataType.MMS.toString());
    msg.setHeader(Headers.TYPE, msgMap.get(MmsConsts.TYPE));
    msg.setHeader(Headers.DATE, msgMap.get(MmsConsts.DATE));
    msg.setHeader(Headers.THREAD_ID, msgMap.get(MmsConsts.THREAD_ID));
    msg.setHeader(Headers.READ, msgMap.get(MmsConsts.READ));
    msg.setHeader(Headers.BACKUP_TIME, new Date().toGMTString());
    msg.setHeader(Headers.VERSION, PrefStore.getVersion(mContext, true));
    msg.setFlag(Flag.SEEN, mMarkAsRead);

    // deal with attachments
    MimeMultipart body = new MimeMultipart();
    for (BodyPart p : getBodyParts(Uri.withAppendedPath(msgRef, "part"))) {
        body.addBodyPart(p);
    }
    msg.setBody(body);
    return msg;
}

From source file:com.amaze.filemanager.utils.files.FileUtils.java

private static Uri fileToContentUri(Context context, String path, boolean isDirectory, String volume) {
    final String where = MediaStore.MediaColumns.DATA + " = ?";
    Uri baseUri;/*from   w ww . j  a  v a  2  s.  co m*/
    String[] projection;
    int mimeType = Icons.getTypeOfFile(path, isDirectory);

    switch (mimeType) {
    case Icons.IMAGE:
        baseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        projection = new String[] { BaseColumns._ID };
        break;
    case Icons.VIDEO:
        baseUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        projection = new String[] { BaseColumns._ID };
        break;
    case Icons.AUDIO:
        baseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        projection = new String[] { BaseColumns._ID };
        break;
    default:
        baseUri = MediaStore.Files.getContentUri(volume);
        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 (mimeType == Icons.IMAGE || mimeType == Icons.VIDEO || mimeType == Icons.AUDIO) {
                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

/**
 * Move all the cards from their old decks to the first deck that was added in setup()
 *///w  ww  .  j  a v a  2 s.  co  m
public void testMoveCardsToOtherDeck() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available notes
    final Cursor allNotesCursor = cr.query(FlashCardsContract.Note.CONTENT_URI, null, "tag:" + TEST_TAG, null,
            null);
    assertNotNull(allNotesCursor);
    try {
        assertEquals("Check number of results", mCreatedNotes.size(), allNotesCursor.getCount());
        while (allNotesCursor.moveToNext()) {
            // Now iterate over all cursors
            Uri cardsUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI,
                            allNotesCursor
                                    .getString(allNotesCursor.getColumnIndex(FlashCardsContract.Note._ID))),
                    "cards");
            final Cursor cardsCursor = cr.query(cardsUri, null, null, null, null);
            assertNotNull("Check that there is a valid cursor after query for cards", cardsCursor);
            try {
                assertTrue("Check that there is at least one result for cards", cardsCursor.getCount() > 0);
                while (cardsCursor.moveToNext()) {
                    long targetDid = mTestDeckIds[0];
                    // Move to test deck
                    ContentValues values = new ContentValues();
                    values.put(FlashCardsContract.Card.DECK_ID, targetDid);
                    Uri cardUri = Uri.withAppendedPath(cardsUri, cardsCursor
                            .getString(cardsCursor.getColumnIndex(FlashCardsContract.Card.CARD_ORD)));
                    cr.update(cardUri, values, null, null);
                    Cursor movedCardCur = cr.query(cardUri, null, null, null, null);
                    assertNotNull("Check that there is a valid cursor after moving card", movedCardCur);
                    assertTrue("Move to beginning of cursor after moving card", movedCardCur.moveToFirst());
                    long did = movedCardCur
                            .getLong(movedCardCur.getColumnIndex(FlashCardsContract.Card.DECK_ID));
                    assertEquals("Make sure that card is in new deck", targetDid, did);
                }
            } finally {
                cardsCursor.close();
            }
        }
    } finally {
        allNotesCursor.close();
    }
}

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

/**
 * ?//from   www  . j av a2s . co m
 *
 * @param comparisonMsg
 *            ??
 * @param folderType
 *            
 * @param startIndex
 *            
 * @param endIndex
 *            ?
 * @return ?
 */
private JSONArray findMessages(JSONObject comparisonMsg, String folderType, int startIndex, int endIndex)
        throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    ArrayList<String> projections = new ArrayList<String>();
    projections.add("_id");
    projections.add("subject");
    projections.add("address");
    projections.add("body");
    ArrayList<String> projectionsValue = new ArrayList<String>();
    projectionsValue.add(comparisonMsg.optString("messageId"));
    projectionsValue.add(comparisonMsg.optString("subject"));
    projectionsValue.add(comparisonMsg.optString("destinationAddresses"));
    projectionsValue.add(comparisonMsg.optString("body"));

    StringBuilder selection = XUtils.constructSelectionStatement(projections, projectionsValue);

    int isRead = comparisonMsg.getInt("isRead");
    if (-1 != isRead) {
        if (null == selection) {
            selection = new StringBuilder();
        } else {
            selection.append(" AND ");
        }
        selection.append("read");
        selection.append("=");
        selection.append(isRead);
    }
    String selectionStr = null;
    if (null != selection) {
        selectionStr = selection.toString();
    }

    folderType = folderType.toLowerCase();
    Uri findUri = Uri.withAppendedPath(mSMSContentUri, folderType);
    JSONArray messages = new JSONArray();
    try {
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(findUri, null, selectionStr, null, null);
        if (null == cursor) {
            return messages;
        }
        int count = endIndex - startIndex + 1;
        if (cursor.moveToPosition(startIndex)) {
            do {
                JSONObject message = getMessageFromCursor(cursor);
                messages.put(message);
                count--;
            } while (cursor.moveToNext() && count > 0);
        }
        cursor.close();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return messages;
}

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

protected void sendClientPhotos(SyncContext context, ContentProvider clientDiffs, Object syncInfo,
        SyncResult syncResult) {/*from w  w  w.ja v a 2s . c  om*/
    Entry entry = new MediaEntry();

    GDataServiceClient client = getGDataServiceClient();
    String authToken = getAuthToken();
    ContentResolver cr = getContext().getContentResolver();
    final String account = getAccount();

    Cursor c = clientDiffs.query(Photos.CONTENT_URI, null /* all columns */, null /* no where */,
            null /* no where args */, null /* default sort order */);
    try {
        int personColumn = c.getColumnIndexOrThrow(Photos.PERSON_ID);
        int dataColumn = c.getColumnIndexOrThrow(Photos.DATA);
        int numRows = c.getCount();
        while (c.moveToNext()) {
            if (mSyncCanceled) {
                if (Config.LOGD)
                    Log.d(TAG, "stopping since the sync was canceled");
                break;
            }

            entry.clear();
            context.setStatusText("Updating, " + (numRows - 1) + " to go");

            cursorToBaseEntry(entry, account, c);
            String editUrl = entry.getEditUri();

            if (TextUtils.isEmpty(editUrl)) {
                if (Config.LOGD) {
                    Log.d(TAG, "skipping photo edit for unsynced contact");
                }
                continue;
            }

            // Send the request and receive the response
            InputStream inputStream = null;
            byte[] imageData = c.getBlob(dataColumn);
            if (imageData != null) {
                inputStream = new ByteArrayInputStream(imageData);
            }
            Uri photoUri = Uri.withAppendedPath(People.CONTENT_URI,
                    c.getString(personColumn) + "/" + Photos.CONTENT_DIRECTORY);
            try {
                if (inputStream != null) {
                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "Updating photo " + entry.toString());
                    }
                    ++mPhotoUploads;
                    client.updateMediaEntry(editUrl, inputStream, IMAGE_MIME_TYPE, authToken);
                } else {
                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "Deleting photo " + entry.toString());
                    }
                    client.deleteEntry(editUrl, authToken);
                }

                // Mark that this photo is no longer dirty. The next time we sync (which
                // should be soon), we will get the new version of the photo and whether
                // or not there is a new one to download (e.g. if we deleted our version
                // yet there is an evergreen version present).
                ContentValues values = new ContentValues();
                values.put(Photos.EXISTS_ON_SERVER, inputStream == null ? 0 : 1);
                values.put(Photos._SYNC_DIRTY, 0);
                if (cr.update(photoUri, values, null /* no where */, null /* no where args */) != 1) {
                    Log.e(TAG, "error updating photo " + photoUri + " with values " + values);
                    syncResult.stats.numParseExceptions++;
                } else {
                    syncResult.stats.numUpdates++;
                }
                continue;
            } catch (ParseException e) {
                Log.e(TAG, "parse error during update of " + ", skipping");
                syncResult.stats.numParseExceptions++;
            } catch (IOException e) {
                if (Config.LOGD) {
                    Log.d(TAG, "io error during update of " + entry.toString() + ", skipping");
                }
                syncResult.stats.numIoExceptions++;
            } catch (HttpException e) {
                switch (e.getStatusCode()) {
                case HttpException.SC_UNAUTHORIZED:
                    if (syncResult.stats.numAuthExceptions == 0) {
                        if (Config.LOGD) {
                            Log.d(TAG, "auth error during update of " + entry + ", skipping");
                        }
                    }
                    syncResult.stats.numAuthExceptions++;
                    try {
                        GoogleLoginServiceBlockingHelper.invalidateAuthToken(getContext(), authToken);
                    } catch (GoogleLoginServiceNotFoundException e1) {
                        if (Config.LOGD) {
                            Log.d(TAG, "could not invalidate auth token", e1);
                        }
                    }
                    return;

                case HttpException.SC_CONFLICT:
                    if (Config.LOGD) {
                        Log.d(TAG, "conflict detected during update of " + entry + ", skipping");
                    }
                    syncResult.stats.numConflictDetectedExceptions++;
                    break;
                case HttpException.SC_BAD_REQUEST:
                case HttpException.SC_FORBIDDEN:
                case HttpException.SC_NOT_FOUND:
                case HttpException.SC_INTERNAL_SERVER_ERROR:
                default:
                    if (Config.LOGD) {
                        Log.d(TAG, "error " + e.getMessage() + " during update of " + entry.toString()
                                + ", skipping");
                    }
                    syncResult.stats.numIoExceptions++;
                }
            }
        }
    } finally {
        c.close();
    }
}

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

/**
 * ?//from w ww . j a v  a2s. c om
 * @param comparisonMsg   ??
 * @param folderType      
 * @param startIndex      
 * @param endIndex        ?
 * @return                ?
 */
private JSONArray findMessages(JSONObject comparisonMsg, String folderType, int startIndex, int endIndex)
        throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    ArrayList<String> projections = new ArrayList<String>();
    projections.add("_id");
    projections.add("subject");
    projections.add("address");
    projections.add("body");
    ArrayList<String> projectionsValue = new ArrayList<String>();
    projectionsValue.add(comparisonMsg.optString("messageId"));
    projectionsValue.add(comparisonMsg.optString("subject"));
    projectionsValue.add(comparisonMsg.optString("destinationAddresses"));
    projectionsValue.add(comparisonMsg.optString("body"));

    StringBuilder selection = XUtils.constructSelectionStatement(projections, projectionsValue);

    int isRead = comparisonMsg.getInt("isRead");
    if (-1 != isRead) {
        if (null == selection) {
            selection = new StringBuilder();
        } else {
            selection.append(" AND ");
        }
        selection.append("read");
        selection.append("=");
        selection.append(isRead);
    }
    String selectionStr = null;
    if (null != selection) {
        selectionStr = selection.toString();
    }

    folderType = folderType.toLowerCase();
    Uri findUri = Uri.withAppendedPath(mSMSContentUri, folderType);
    JSONArray messages = new JSONArray();
    try {
        ContentResolver resolver = getContext().getContentResolver();
        Cursor cursor = resolver.query(findUri, null, selectionStr, null, null);
        if (null == cursor) {
            return messages;
        }
        int count = endIndex - startIndex + 1;
        if (cursor.moveToPosition(startIndex)) {
            do {
                JSONObject message = getMessageFromCursor(cursor);
                messages.put(message);
                count--;
            } while (cursor.moveToNext() && count > 0);
        }
        cursor.close();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return messages;
}

From source file:org.musicmod.android.app.MusicPlaybackActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Intent intent;// ww  w .j av a  2s.  c  o m
    switch (item.getItemId()) {
    case ADD_TO_PLAYLIST:
        intent = new Intent(INTENT_ADD_TO_PLAYLIST);
        long[] list_to_be_added = new long[1];
        list_to_be_added[0] = MusicUtils.getCurrentAudioId();
        intent.putExtra(INTENT_KEY_LIST, list_to_be_added);
        startActivity(intent);
        break;
    case EQUALIZER:
        intent = new Intent(INTENT_EQUALIZER);
        startActivity(intent);
        break;
    case SLEEP_TIMER:
        intent = new Intent(INTENT_SLEEP_TIMER);
        startActivity(intent);
        break;
    case DELETE_ITEMS:
        intent = new Intent(INTENT_DELETE_ITEMS);
        Bundle bundle = new Bundle();
        bundle.putString(INTENT_KEY_PATH, Uri.withAppendedPath(Audio.Media.EXTERNAL_CONTENT_URI,
                Uri.encode(String.valueOf(MusicUtils.getCurrentAudioId()))).toString());
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    case SETTINGS:
        intent = new Intent(INTENT_APPEARANCE_SETTINGS);
        startActivity(intent);
        break;
    case GOTO_HOME:
        intent = new Intent(INTENT_MUSIC_BROWSER);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        break;
    case ADD_TO_FAVORITES:
        toggleFavorite();
        break;
    }

    return super.onOptionsItemSelected(item);
}

From source file:android.com.example.contactslist.ui.ContactsListFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {

    // If this is the loader for finding contacts in the Contacts Provider
    // (the only one supported)
    if (id == ContactsQuery.QUERY_ID) {
        Uri contentUri;//  w w w. ja va 2 s .c om

        // There are two types of searches, one which displays all contacts and
        // one which filters contacts by a search query. If mSearchTerm is set
        // then a search query has been entered and the latter should be used.

        if (mSearchTerm == null) {
            // Since there's no search string, use the content URI that searches the entire
            // Contacts table
            contentUri = ContactsQuery.CONTENT_URI;
        } else {
            // Since there's a search string, use the special content Uri that searches the
            // Contacts table. The URI consists of a base Uri and the search string.
            contentUri = Uri.withAppendedPath(ContactsQuery.FILTER_URI, Uri.encode(mSearchTerm));
        }

        // Returns a new CursorLoader for querying the Contacts table. No arguments are used
        // for the selection clause. The search string is either encoded onto the content URI,
        // or no contacts search string is used. The other search criteria are constants. See
        // the ContactsQuery interface.
        return new CursorLoader(getActivity(), contentUri, ContactsQuery.PROJECTION, ContactsQuery.SELECTION,
                null, ContactsQuery.SORT_ORDER);
    }

    Log.e(TAG, "onCreateLoader - incorrect ID provided (" + id + ")");
    return null;
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/** 
 * Takes a JSON contact object and loops through the available addresses.  If the  
 * address has an id that is not equal to null the address will be updated in the database.
 * If the id is null then we treat it as a new address.
 * //w ww .j a  v  a 2 s.  c  om
 * @param contact the contact to extract the addresses from
 * @param uri the base URI for this contact.
 */
private void saveAddresses(JSONObject contact, Uri uri) {
    ContentValues values = new ContentValues();
    Uri newUri = Uri.withAppendedPath(uri, Contacts.People.ContactMethods.CONTENT_DIRECTORY);
    String id = null;
    try {
        JSONArray entries = contact.getJSONArray("addresses");
        if (entries != null && entries.length() > 0) {
            JSONObject entry;
            values.put(Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL);
            for (int i = 0; i < entries.length(); i++) {
                entry = entries.getJSONObject(i);
                id = getJsonString(entry, "id");

                String address = getJsonString(entry, "formatted");
                if (address != null) {
                    values.put(Contacts.ContactMethods.DATA, address);
                } else {
                    values.put(Contacts.ContactMethods.DATA, createAddressString(entry));
                }

                if (id == null) {
                    Uri contactUpdate = mApp.getContentResolver().insert(newUri, values);
                } else {
                    Uri tempUri = Uri.withAppendedPath(newUri, id);
                    mApp.getContentResolver().update(tempUri, values, null, null);
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not save address = " + e.getMessage());
    }
}