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.example.linhdq.test.documents.viewing.single.DocumentTextFragment.java

void saveIfTextHasChanged() {
    if (mHasTextChanged) {
        mHasTextChanged = false;//  w  w w.  j  a v a 2 s.  c o  m
        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());
        NewDocumentActivity.SaveDocumentTask saveTask = new NewDocumentActivity.SaveDocumentTask(getActivity(),
                ids, texts);
        saveTask.execute();
    }
}

From source file:com.android.messaging.mmslib.util.PduCache.java

@Override
public synchronized PduCacheEntry purge(Uri uri) {
    int match = URI_MATCHER.match(uri);
    switch (match) {
    case MMS_ALL_ID:
        return purgeSingleEntry(uri);
    case MMS_INBOX_ID:
    case MMS_SENT_ID:
    case MMS_DRAFTS_ID:
    case MMS_OUTBOX_ID:
        String msgId = uri.getLastPathSegment();
        return purgeSingleEntry(Uri.withAppendedPath(Mms.CONTENT_URI, msgId));
    // Implicit batch of purge, return null.
    case MMS_ALL:
    case MMS_CONVERSATION:
        purgeAll();/*  w  w  w. j  ava  2  s. co  m*/
        return null;
    case MMS_INBOX:
    case MMS_SENT:
    case MMS_DRAFTS:
    case MMS_OUTBOX:
        purgeByMessageBox(MATCH_TO_MSGBOX_ID_MAP.get(match));
        return null;
    case MMS_CONVERSATION_ID:
        purgeByThreadId(ContentUris.parseId(uri));
        return null;
    default:
        return null;
    }
}

From source file:com.battlelancer.seriesguide.ui.CheckinActivity.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Uri baseUri;//from   w  w w  . ja v  a2s . c om
    if (mSearchFilter != null) {
        baseUri = Uri.withAppendedPath(Shows.CONTENT_FILTER_URI, Uri.encode(mSearchFilter));
    } else {
        baseUri = Shows.CONTENT_URI;
    }

    // query selects shows with next episodes before this point in time
    // it does not make sense to check into episodes further in the future
    String customTimeInOneHour = String.valueOf(TimeTools.getCurrentTime(this) + DateUtils.HOUR_IN_MILLIS);

    return new CursorLoader(this, baseUri, CheckinQuery.PROJECTION, CheckinQuery.SELECTION,
            new String[] { customTimeInOneHour }, ShowsDistillationSettings.ShowsSortOrder.EPISODE_REVERSE);
}

From source file:com.piusvelte.sonet.core.SonetNotifications.java

@Override
protected void onListItemClick(ListView list, final View view, int position, final long id) {
    super.onListItemClick(list, view, position, id);
    // load SonetComments.java, the notification will be clear there
    startActivityForResult(//www. ja v  a2 s.  com
            Sonet.getPackageIntent(this, SonetComments.class)
                    .setData(Uri.withAppendedPath(Notifications.getContentUri(this), Long.toString(id))),
            RESULT_REFRESH);
}

From source file:ca.rmen.android.scrumchatter.meeting.detail.MeetingFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.v(TAG, "onCreateView: savedInstanceState = " + savedInstanceState);
    // Create our views
    mBinding = DataBindingUtil.inflate(inflater, R.layout.meeting_fragment, container, false);
    mBinding.setMeetingStopListener(new MeetingStopListener());
    mBinding.recyclerViewContent.recyclerView
            .setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
    mMeetingId = getArguments().getLong(Meetings.EXTRA_MEETING_ID);
    if (!TAG.endsWith("" + mMeetingId))
        TAG += "/" + mMeetingId;

    // Load the meeting and register for DB changes on the meeting
    Uri uri = Uri.withAppendedPath(MeetingColumns.CONTENT_URI, String.valueOf(mMeetingId));
    getActivity().getContentResolver().registerContentObserver(uri, false, mMeetingObserver);
    loadMeeting();/*from  www  . j  a  v a  2  s.  c  om*/
    return mBinding.getRoot();
}

From source file:com.portol.common.utils.Util.java

/**
 * Merges a uri and a string to produce a new uri.
 * <p>/*ww  w. ja  va2 s. c  om*/
 * The uri is built according to the following rules:
 * <ul>
 * <li>If {@code baseUri} is null or if {@code stringUri} is absolute, then {@code baseUri} is
 * ignored and the uri consists solely of {@code stringUri}.
 * <li>If {@code stringUri} is null, then the uri consists solely of {@code baseUrl}.
 * <li>Otherwise, the uri consists of the concatenation of {@code baseUri} and {@code stringUri}.
 * </ul>
 *
 * @param baseUri A uri that can form the base of the merged uri.
 * @param stringUri A relative or absolute uri in string form.
 * @return The merged uri.
 */
public static Uri getMergedUri(Uri baseUri, String stringUri) {
    if (stringUri == null) {
        return baseUri;
    }
    if (baseUri == null) {
        return Uri.parse(stringUri);
    }
    if (stringUri.startsWith("/")) {
        stringUri = stringUri.substring(1);
        return new Uri.Builder().scheme(baseUri.getScheme()).authority(baseUri.getAuthority())
                .appendEncodedPath(stringUri).build();
    }
    Uri uri = Uri.parse(stringUri);
    if (uri.isAbsolute()) {
        return uri;
    }
    return Uri.withAppendedPath(baseUri, stringUri);
}

From source file:com.mpower.mintel.android.tasks.InstanceUploaderTask.java

@Override
protected HashMap<String, String> doInBackground(Long... values) {
    mResults = new HashMap<String, String>();

    String postResponse;/*from   w  w w  . j ava  2  s .  c  om*/
    String selection = InstanceColumns._ID + "=?";
    String[] selectionArgs = new String[values.length];
    for (int i = 0; i < values.length; i++) {
        if (i != values.length - 1) {
            selection += " or " + InstanceColumns._ID + "=?";
        }
        selectionArgs[i] = values[i].toString();
    }

    // get shared HttpContext so that authentication and cookies are
    // retained.
    HttpContext localContext = MIntel.getInstance().getHttpContext();
    HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);

    Map<URI, URI> uriRemap = new HashMap<URI, URI>();

    Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection,
            selectionArgs, null);

    if (c.getCount() > 0) {
        c.moveToPosition(-1);
        next_submission: while (c.moveToNext()) {
            if (isCancelled()) {
                return mResults;
            }
            publishProgress(c.getPosition() + 1, c.getCount());
            String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
            String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
            Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);

            String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
            if (urlString == null) {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MIntel.getInstance());
                urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
                urlString = urlString + WebUtils.URL_PART_SUBMISSION;
            }

            ContentValues cv = new ContentValues();
            URI u = null;
            try {
                URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
                u = url.toURI();
            } catch (MalformedURLException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (URISyntaxException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            }

            boolean openRosaServer = false;
            if (uriRemap.containsKey(u)) {
                // we already issued a head request and got a response,
                // so we know the proper URL to send the submission to
                // and the proper scheme. We also know that it was an
                // OpenRosa compliant server.
                openRosaServer = true;
                u = uriRemap.get(u);
            } else {
                // we need to issue a head request
                HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);

                // prepare response
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httpHead, localContext);
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 401) {
                        // we need authentication, so stop and return what
                        // we've
                        // done so far.
                        mAuthRequestingServer = u;
                        return null;
                    } else if (statusCode == 204) {
                        Header[] locations = response.getHeaders("Location");
                        if (locations != null && locations.length == 1) {
                            try {
                                URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8"));
                                URI uNew = url.toURI();
                                if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
                                    openRosaServer = true;
                                    // trust the server to tell us a new
                                    // location
                                    // ... and possibly to use https
                                    // instead.
                                    uriRemap.put(u, uNew);
                                    u = uNew;
                                } else {
                                    // Don't follow a redirection attempt to
                                    // a different host.
                                    // We can't tell if this is a spoof or
                                    // not.
                                    mResults.put(id,
                                            fail + "Unexpected redirection attempt to a different host: "
                                                    + uNew.toString());
                                    cv.put(InstanceColumns.STATUS,
                                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                    continue;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                mResults.put(id, fail + urlString + " " + e.getMessage());
                                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                continue;
                            }
                        }
                    } else {
                        // may be a server that does not handle
                        try {
                            // have to read the stream in order to reuse the
                            // connection
                            InputStream is = response.getEntity().getContent();
                            // read to end of stream...
                            final long count = 1024L;
                            while (is.skip(count) == count)
                                ;
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        Log.w(t, "Status code on Head request: " + statusCode);
                        if (statusCode >= 200 && statusCode <= 299) {
                            mResults.put(id, fail
                                    + "Invalid status code on Head request.  If you have a web proxy, you may need to login to your network. ");
                            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                            continue;
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Client Protocol Exception");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (ConnectTimeoutException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Connection Timeout");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + "Generic Exception");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                }
            }

            // At this point, we may have updated the uri to use https.
            // This occurs only if the Location header keeps the host name
            // the same. If it specifies a different host name, we error
            // out.
            //
            // And we may have set authentication cookies in our
            // cookiestore (referenced by localContext) that will enable
            // authenticated publication to the server.
            //
            // get instance file
            File instanceFile = new File(instance);

            if (!instanceFile.exists()) {
                mResults.put(id, fail + "instance XML file does not exist!");
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            }

            // find all files in parent directory
            File[] allFiles = instanceFile.getParentFile().listFiles();

            // add media files
            List<File> files = new ArrayList<File>();
            for (File f : allFiles) {
                String fileName = f.getName();

                int dotIndex = fileName.lastIndexOf(".");
                String extension = "";
                if (dotIndex != -1) {
                    extension = fileName.substring(dotIndex + 1);
                }

                if (fileName.startsWith(".")) {
                    // ignore invisible files
                    continue;
                }
                if (fileName.equals(instanceFile.getName())) {
                    continue; // the xml file has already been added
                } else if (openRosaServer) {
                    files.add(f);
                } else if (extension.equals("jpg")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("3gpp")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("3gp")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("mp4")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("amr")) { // legacy 0.9x
                    files.add(f);
                } else {
                    Log.w(t, "unrecognized file type " + f.getName());
                }
            }

            postResponse = "";
            boolean first = true;
            int j = 0;
            while (j < files.size() || first) {
                first = false;

                HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth);

                MimeTypeMap m = MimeTypeMap.getSingleton();

                long byteCount = 0L;

                // mime post
                MultipartEntity entity = new MultipartEntity();

                // add the submission file first...
                FileBody fb = new FileBody(instanceFile, "text/xml");
                entity.addPart("xml_submission_file", fb);
                Log.i(t, "added xml_submission_file: " + instanceFile.getName());
                byteCount += instanceFile.length();

                for (; j < files.size(); j++) {
                    File f = files.get(j);
                    String fileName = f.getName();
                    int idx = fileName.lastIndexOf(".");
                    String extension = "";
                    if (idx != -1) {
                        extension = fileName.substring(idx + 1);
                    }
                    String contentType = m.getMimeTypeFromExtension(extension);

                    // we will be processing every one of these, so
                    // we only need to deal with the content type
                    // determination...
                    if (extension.equals("xml")) {
                        fb = new FileBody(f, "text/xml");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added xml file " + f.getName());
                    } else if (extension.equals("jpg")) {
                        fb = new FileBody(f, "image/jpeg");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added image file " + f.getName());
                    } else if (extension.equals("3gpp")) {
                        fb = new FileBody(f, "audio/3gpp");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added audio file " + f.getName());
                    } else if (extension.equals("3gp")) {
                        fb = new FileBody(f, "video/3gpp");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added video file " + f.getName());
                    } else if (extension.equals("mp4")) {
                        fb = new FileBody(f, "video/mp4");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added video file " + f.getName());
                    } else if (extension.equals("csv")) {
                        fb = new FileBody(f, "text/csv");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added csv file " + f.getName());
                    } else if (f.getName().endsWith(".amr")) {
                        fb = new FileBody(f, "audio/amr");
                        entity.addPart(f.getName(), fb);
                        Log.i(t, "added audio file " + f.getName());
                    } else if (extension.equals("xls")) {
                        fb = new FileBody(f, "application/vnd.ms-excel");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added xls file " + f.getName());
                    } else if (contentType != null) {
                        fb = new FileBody(f, contentType);
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName());
                    } else {
                        contentType = "application/octet-stream";
                        fb = new FileBody(f, contentType);
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
                    }

                    // we've added at least one attachment to the request...
                    if (j + 1 < files.size()) {
                        if (byteCount + files.get(j + 1).length() > 10000000L) {
                            // the next file would exceed the 10MB
                            // threshold...
                            Log.i(t, "Extremely long post is being split into multiple posts");
                            try {
                                StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
                                entity.addPart("*isIncomplete*", sb);
                            } catch (Exception e) {
                                e.printStackTrace(); // never happens...
                            }
                            ++j; // advance over the last attachment
                                 // added...
                            break;
                        }
                    }
                }

                httppost.setEntity(entity);

                // prepare response and return uploaded
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httppost, localContext);
                    int responseCode = response.getStatusLine().getStatusCode();

                    // try {
                    // // have to read the stream in order to reuse the
                    // connection
                    // InputStream is = response.getEntity().getContent();
                    // // read to end of stream...
                    // final long count = 1024L;
                    // while (is.skip(count) == count)
                    // ;
                    // is.close();
                    // } catch (IOException e) {
                    // e.printStackTrace();
                    // } catch (Exception e) {
                    // e.printStackTrace();
                    // }

                    HttpEntity httpEntity = response.getEntity();
                    try {
                        postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Log.i(t, "Response code:" + responseCode);
                    // verify that the response was a 201 or 202.
                    // If it wasn't, the submission has failed.
                    if (responseCode != 201 && responseCode != 202) {
                        if (responseCode == 200) {
                            mResults.put(id, fail + "Network login failure? Again?");
                        } else {
                            if (postResponse.length() > 0) {
                                mResults.put(id, postResponse);
                            } else {
                                mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " ("
                                        + responseCode + ") at " + urlString);
                            }
                        }
                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                        continue next_submission;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + " " + e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue next_submission;
                }
            }

            // if it got here, it must have worked
            if (postResponse.length() > 0) {
                // Custom msg from server
                mResults.put(id, postResponse);
            } else {
                // There is no response from server, use default string
                mResults.put(id, MIntel.getInstance().getString(R.string.success));
            }
            // mResults.put(id,
            // MIntel.getInstance().getString(R.string.success));
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);

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

    } // end while

    return mResults;
}

From source file:org.andrico.andrico.facebook.FBBase.java

/**
 * Generate a URL authorizing a requested extended preference.
 * //  w  w  w.  ja  va  2s .  c  om
 * @param Which preference to generate the request URL for.
 * @return
 */
public Uri authorizeExtendedPreferenceUrl(String extPerm, String next, String nextCancel) {
    TreeMap<String, String> parameters = new TreeMap<String, String>();
    parameters.put("api_key", mApiKey);
    parameters.put("ext_perm", extPerm);
    parameters.put("popup", "1");
    parameters.put("v", "1.0");
    if (next != null) {
        parameters.put("next", next);
    }
    if (nextCancel != null) {
        parameters.put("next_cancel", nextCancel);
    }

    Uri url = Uri.withAppendedPath(WWW_URI, "authorize.php?" + FBMethod.urlParameters(parameters));
    Log.e(LOG, "Generated setStatus authorization URL: " + url);
    return url;
}

From source file:com.example.fragmentexercise.ContactsAdapter.java

/**
 * Load a contact photo thumbnail and return it as a Bitmap, resizing the
 * image to the provided image dimensions as needed.
 * /*  w  w w  .  java  2 s. c  o  m*/
 * @param photoData
 *            photo ID Prior to Honeycomb, the contact's _ID value. For
 *            Honeycomb and later, the value of PHOTO_THUMBNAIL_URI.
 * @return A thumbnail Bitmap, sized to the provided width and height.
 *         Returns null if the thumbnail is not found.
 */
private Bitmap loadContactPhotoThumbnail(String photoData) {
    // Creates an asset file descriptor for the thumbnail file.
    AssetFileDescriptor afd = null;
    // try-catch block for file not found
    try {
        // Creates a holder for the URI.
        Uri thumbUri;
        // If Android 3.0 or later
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Sets the URI from the incoming PHOTO_THUMBNAIL_URI
            thumbUri = Uri.parse(photoData);
        } else {
            // Prior to Android 3.0, constructs a photo Uri using _ID
            /*
             * Creates a contact URI from the Contacts content URI incoming
             * photoData (_ID)
             */
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
            /*
             * Creates a photo URI by appending the content URI of
             * Contacts.Photo.
             */
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }

        /*
         * Retrieves an AssetFileDescriptor object for the thumbnail URI
         * using ContentResolver.openAssetFileDescriptor
         */
        afd = mContext.getContentResolver().openAssetFileDescriptor(thumbUri, "r");
        /*
         * Gets a file descriptor from the asset file descriptor. This
         * object can be used across processes.
         */
        FileDescriptor fileDescriptor = afd.getFileDescriptor();
        // Decode the photo file and return the result as a Bitmap
        // If the file descriptor is valid
        if (fileDescriptor != null) {
            // Decodes the bitmap
            return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, null);
        }
        // If the file isn't found
    } catch (FileNotFoundException e) {
        /*
         * Handle file not found errors
         */
    }
    // In all cases, close the asset file descriptor
    finally {
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.visva.voicerecorder.utils.Utils.java

public static Uri getContactUriTypeFromPhoneNumber(ContentResolver resolver, String phoneNo, int index) {
    Uri result = null;//from   w w w.ja va2 s  .  co m
    if (phoneNo == "" || "null".equals(phoneNo)) {
        phoneNo = "111111111";
    }
    String[] projection = { ContactsContract.Contacts._ID, ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.PHOTO_URI,
            ContactsContract.PhoneLookup.LOOKUP_KEY };
    Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNo));
    Cursor cursor = resolver.query(lookupUri, projection, null, null, null);
    if (cursor == null)
        return null;
    if (cursor.moveToFirst()) {
        if (cursor.getString(index) != null)
            result = Uri.parse(cursor.getString(index));
    }
    if (cursor != null) {
        cursor.close();
        cursor = null;
    }
    return result;
}