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.android.contacts.common.model.ContactLoader.java

private Contact loadContactEntity(ContentResolver resolver, Uri contactUri) {
    Uri entityUri = Uri.withAppendedPath(contactUri, Contacts.Entity.CONTENT_DIRECTORY);
    Cursor cursor = resolver.query(entityUri, ContactQuery.COLUMNS, null, null, Contacts.Entity.RAW_CONTACT_ID);
    if (cursor == null) {
        Log.e(TAG, "No cursor returned in loadContactEntity");
        return Contact.forNotFound(mRequestedUri);
    }//  www. j  av a2 s.  c  o m

    try {
        if (!cursor.moveToFirst()) {
            cursor.close();
            return Contact.forNotFound(mRequestedUri);
        }

        // Create the loaded contact starting with the header data.
        Contact contact = loadContactHeaderData(cursor, contactUri);

        // Fill in the raw contacts, which is wrapped in an Entity and any
        // status data.  Initially, result has empty entities and statuses.
        long currentRawContactId = -1;
        RawContact rawContact = null;
        ImmutableList.Builder<RawContact> rawContactsBuilder = new ImmutableList.Builder<RawContact>();
        ImmutableMap.Builder<Long, DataStatus> statusesBuilder = new ImmutableMap.Builder<Long, DataStatus>();
        do {
            long rawContactId = cursor.getLong(ContactQuery.RAW_CONTACT_ID);
            if (rawContactId != currentRawContactId) {
                // First time to see this raw contact id, so create a new entity, and
                // add it to the result's entities.
                currentRawContactId = rawContactId;
                rawContact = new RawContact(loadRawContactValues(cursor));
                rawContactsBuilder.add(rawContact);
            }
            if (!cursor.isNull(ContactQuery.DATA_ID)) {
                ContentValues data = loadDataValues(cursor);
                rawContact.addDataItemValues(data);

                if (!cursor.isNull(ContactQuery.PRESENCE) || !cursor.isNull(ContactQuery.STATUS)) {
                    final DataStatus status = new DataStatus(cursor);
                    final long dataId = cursor.getLong(ContactQuery.DATA_ID);
                    statusesBuilder.put(dataId, status);
                }
            }
        } while (cursor.moveToNext());

        contact.setRawContacts(rawContactsBuilder.build());
        contact.setStatuses(statusesBuilder.build());

        return contact;
    } finally {
        cursor.close();
    }
}

From source file:com.navjagpal.fileshare.WebServer.java

@SuppressWarnings("deprecation")
public void processUpload(String folderId, HttpRequest request, DefaultHttpServerConnection serverConnection)
        throws IOException, HttpException {

    /* Find the boundary and the content length. */
    String contentType = request.getFirstHeader("Content-Type").getValue();
    String boundary = contentType.substring(contentType.indexOf("boundary=") + "boundary=".length());
    BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest(
            request.getRequestLine());/*  w  ww.j av a 2s .  c om*/
    serverConnection.receiveRequestEntity(enclosingRequest);

    InputStream input = enclosingRequest.getEntity().getContent();
    MultipartStream multipartStream = new MultipartStream(input, boundary.getBytes());
    String headers = multipartStream.readHeaders();

    /* Get the filename. */
    StringTokenizer tokens = new StringTokenizer(headers, ";", false);
    String filename = null;
    while (tokens.hasMoreTokens() && filename == null) {
        String token = tokens.nextToken().trim();
        if (token.startsWith("filename=")) {
            filename = URLDecoder.decode(token.substring("filename=\"".length(), token.lastIndexOf("\"")),
                    "utf8");
        }
    }

    File uploadDirectory = new File("/sdcard/fileshare/uploads");
    if (!uploadDirectory.exists()) {
        uploadDirectory.mkdirs();
    }

    /* Write the file and add it to the shared folder. */
    File uploadFile = new File(uploadDirectory, filename);
    FileOutputStream output = new FileOutputStream(uploadFile);
    multipartStream.readBodyData(output);
    output.close();

    Uri fileUri = Uri.withAppendedPath(FileProvider.CONTENT_URI, uploadFile.getAbsolutePath());
    Uri folderUri = Uri.withAppendedPath(FileSharingProvider.Folders.CONTENT_URI, folderId);
    FileSharingProvider.addFileToFolder(mContext.getContentResolver(), fileUri, folderUri);
}

From source file:com.intel.xdk.contacts.Contacts.java

public void removeContact(String contactId) {
    if (busy == true) {
        String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.busy',true,true);e.success=false;e.message='busy';document.dispatchEvent(e);";
        injectJS(js);/*www .  jav  a  2s  .  c  om*/
        return;
    }

    try {
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, contactId);
        int rowsDeleted = activity.getContentResolver().delete(uri, null, null);

        if (rowsDeleted > 0) {
            getAllContacts();
            String js = String.format(
                    "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.remove',true,true);e.success=true;e.contactid='%s';document.dispatchEvent(e);",
                    contactId);
            injectJS("javascript: " + js);
        } else {
            String js = String.format(
                    "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.remove',true,true);e.success=false;e.error='error deleting contact';e.contactid='%s';document.dispatchEvent(e);",
                    contactId);
            injectJS("javascript: " + js);
        }
        busy = false;
    } catch (Exception e) {
        System.out.println(e.getStackTrace());
        String errjs = String.format(
                "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.remove',true,true);e.success=false;e.error='contact not found';e.contactid='%s';document.dispatchEvent(e);",
                contactId);
        injectJS("javascript: " + errjs);
        busy = false;
        return;
    }
}

From source file:org.kontalk.data.Contact.java

static Contact _findByUserId(Context context, String userId) {
    ContentResolver cres = context.getContentResolver();
    Cursor c = cres.query(/*from   ww  w  .j  a v a 2s.c  om*/
            Uri.withAppendedPath(Users.CONTENT_URI, userId), new String[] { Users.NUMBER, Users.DISPLAY_NAME,
                    Users.LOOKUP_KEY, Users.CONTACT_ID, Users.REGISTERED, Users.STATUS, Users.BLOCKED, },
            null, null, null);

    if (c.moveToFirst()) {
        final String number = c.getString(0);
        final String name = c.getString(1);
        final String key = c.getString(2);
        final long cid = c.getLong(3);
        final boolean registered = (c.getInt(4) != 0);
        final String status = c.getString(5);
        final boolean blocked = (c.getInt(6) != 0);
        c.close();

        Contact contact = new Contact(cid, key, name, number, userId, blocked);
        contact.mRegistered = registered;
        contact.mStatus = status;

        retrieveKeyInfo(context, contact);

        return contact;
    }
    c.close();
    return null;
}

From source file:cz.maresmar.sfm.utils.ActionUtils.java

/**
 * Deletes all {@link ProviderContract#ACTION_SYNC_STATUS_EDIT} actions
 *
 * @param context Some valid context// w  w w. jav a2s  .co m
 * @param userUri User Uri prefix
 */
@WorkerThread
public static void discardEdits(@NonNull Context context, @NonNull Uri userUri) {
    Uri actionUri = Uri.withAppendedPath(userUri, ProviderContract.ACTION_PATH);
    int affectedRows = context.getContentResolver().delete(actionUri,
            ProviderContract.Action.SYNC_STATUS + " == " + ProviderContract.ACTION_SYNC_STATUS_EDIT, null);

    if (BuildConfig.DEBUG && affectedRows == 0) {
        Timber.w("Should delete at least one edit");
    }
}

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

/**
 * ??//from  www  .  j  av a  2s .c  o  m
 *
 * @param messageType
 *            ?MMS,SMS,Email
 * @param folderType
 *            
 * @return ?
 */
private JSONArray getAllMessages(String messageType, String folderType) throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }
    JSONArray messages = new JSONArray();
    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 messages;
        }
        if (!cursor.moveToFirst()) {
            cursor.close();
            return messages;
        }
        do {
            // TODO:?SIM??
            JSONObject message = getMessageFromCursor(cursor);
            messages.put(message);
        } while (cursor.moveToNext());
        cursor.close();

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

From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactDetailFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    //       Log.v(ParserApplication.getDebugTag(), "In onCreateLoader and the id is: "+Integer.toString(id));
    switch (id) {
    // Two main queries to load the required information
    case ContactDetailQuery.QUERY_ID:
        // This query loads main contact details, see
        // ContactDetailQuery for more information.
        //               Log.v(ParserApplication.getDebugTag(), mContactUri.toString());
        return new CursorLoader(getActivity(), mContactUri, ContactDetailQuery.PROJECTION, null, null, null);
    case ContactAddressQuery.QUERY_ID:
        // This query loads contact address details, see
        // ContactAddressQuery for more information.
        final Uri addressUri = Uri.withAppendedPath(mContactUri, Contacts.Data.CONTENT_DIRECTORY);
        return new CursorLoader(getActivity(), addressUri, ContactAddressQuery.PROJECTION,
                ContactAddressQuery.SELECTION, null, null);
    case ContactPhoneQuery.QUERY_ID:
        // This query loads contact phone details, see
        // ContactPhoneQuery for more information.
        final Uri phoneUri = Uri.withAppendedPath(mContactUri, Contacts.Data.CONTENT_DIRECTORY);
        return new CursorLoader(getActivity(), phoneUri, ContactPhoneQuery.PROJECTION,
                ContactPhoneQuery.SELECTION, null, null);
    }/*  w  ww .j  av  a 2 s. co m*/
    return null;
}

From source file:es.example.contacts.ui.ContactDetailFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    // If this fragment was cleared while the query was running
    // eg. from from a call like setContact(uri) then don't do
    // anything.//from  w  w w. ja v a  2 s .  c  om
    if (mContactUri == null) {
        return;
    }

    switch (loader.getId()) {
    case ContactDetailQuery.QUERY_ID:
        // Moves to the first row in the Cursor
        if (data.moveToFirst()) {
            // For the contact details query, fetches the contact display name.
            // ContactDetailQuery.DISPLAY_NAME maps to the appropriate display
            // name field based on OS version.
            final String contactName = data.getString(ContactDetailQuery.DISPLAY_NAME);
            displayName = contactName;
            id = data.getString(ContactDetailQuery.ID);
            if (mIsTwoPaneLayout && mContactName != null) {
                // In the two pane layout, there is a dedicated TextView
                // that holds the contact name.
                mContactName.setText(contactName);
            } else {
                // In the single pane layout, sets the activity title
                // to the contact name. On HC+ this will be set as
                // the ActionBar title text.
                getActivity().setTitle(contactName);
            }
        }
        break;
    case ContactAddressQuery.QUERY_ID:
        // This query loads the contact address details. More than
        // one contact address is possible, so move each one to a
        // LinearLayout in a Scrollview so multiple addresses can
        // be scrolled by the user.

        // Each LinearLayout has the same LayoutParams so this can
        // be created once and used for each address.
        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        // Clears out the details layout first in case the details
        // layout has addresses from a previous data load still
        // added as children.
        mDetailsLayout.removeAllViews();

        // Loops through all the rows in the Cursor
        if (data.moveToFirst()) {
            do {
                final Uri uri = Uri.withAppendedPath(mContactUri,
                        ContactsContract.RawContacts.Data.CONTENT_DIRECTORY);
                ContentResolver cr = getActivity().getContentResolver();

                Cursor cur = cr.query(uri, ContactPhoneQuery.PROJECTION, ContactPhoneQuery.SELECTION, null,
                        null);
                try {
                    if (cur.moveToFirst()) {
                        // Builds the address layout
                        final Uri uriData = Uri.parse("content://com.android.contacts/data");
                        Cursor curData = cr.query(Data.CONTENT_URI, ContactData1Query.PROJECTION,
                                ContactData1Query.SELECTION, null, null);
                        try {
                            if (curData.getCount() == 0) {
                                final LinearLayout layout = buildAddressLayout(
                                        data.getInt(ContactAddressQuery.TYPE),
                                        data.getString(ContactAddressQuery.LABEL),
                                        data.getString(ContactAddressQuery.ADDRESS),
                                        cur.getString(ContactPhoneQuery.PHONE), null,
                                        data.getString(ContactAddressQuery.CONTACT_ID), displayName);
                                // Adds the new address layout to the details layout
                                mDetailsLayout.addView(layout, layoutParams);

                            } else {
                                if (curData.moveToFirst()) {

                                    final LinearLayout layout = buildAddressLayout(
                                            curData.getInt(ContactAddressQuery.ID),
                                            data.getString(ContactAddressQuery.LABEL),
                                            data.getString(ContactAddressQuery.ADDRESS),
                                            cur.getString(ContactPhoneQuery.PHONE),
                                            curData.getString(ContactData1Query.DATA1),
                                            data.getString(ContactAddressQuery.CONTACT_ID), displayName);
                                    // Adds the new address layout to the details layout
                                    mDetailsLayout.addView(layout, layoutParams);
                                }
                            }
                        } finally {
                            if (curData != null)
                                curData.close();
                        }
                    }
                } finally {
                    if (cur != null)
                        cur.close();
                }
            } while (data.moveToNext());
            data.close();
        } else {
            // If nothing found, adds an empty address layout
            mDetailsLayout.addView(buildEmptyAddressLayout(), layoutParams);
        }

        break;
    }
}

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

/**
 * ??//from   ww w.j a v a 2  s  .  c o  m
 * @param messageType       ?MMS,SMS,Email
 * @param  folderType       
 * @return                  ?
 */
private JSONArray getAllMessages(String messageType, String folderType) throws JSONException {
    //TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }
    JSONArray messages = new JSONArray();
    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 messages;
        }
        if (!cursor.moveToFirst()) {
            cursor.close();
            return messages;
        }
        do {
            //TODO:?SIM??
            JSONObject message = getMessageFromCursor(cursor);
            messages.put(message);
        } while (cursor.moveToNext());
        cursor.close();

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

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

/**
 * Query .../models URI/* w  w  w.j av a 2  s. co m*/
 */
public void testQueryAllModels() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available models
    final Cursor allModels = cr.query(FlashCardsContract.Model.CONTENT_URI, null, null, null, null);
    assertNotNull(allModels);
    try {
        assertTrue("Check that there is at least one result", allModels.getCount() > 0);
        while (allModels.moveToNext()) {
            long modelId = allModels.getLong(allModels.getColumnIndex(FlashCardsContract.Model._ID));
            Uri modelUri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, Long.toString(modelId));
            final Cursor singleModel = cr.query(modelUri, null, null, null, null);
            assertNotNull(singleModel);
            try {
                assertEquals("Check that there is exactly one result", 1, singleModel.getCount());
                assertTrue("Move to beginning of cursor", singleModel.moveToFirst());
                String nameFromModels = allModels
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME));
                String nameFromModel = singleModel
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME));
                assertEquals("Check that model names are the same", nameFromModel, nameFromModels);
                String flds = allModels
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES));
                assertTrue("Check that valid number of fields", Utils.splitFields(flds).length >= 1);
                Integer numCards = allModels
                        .getInt(allModels.getColumnIndex(FlashCardsContract.Model.NUM_CARDS));
                assertTrue("Check that valid number of cards", numCards >= 1);
            } finally {
                singleModel.close();
            }
        }
    } finally {
        allModels.close();
    }
}