android.net.Uri

Here are the examples of the java api class android.net.Uri taken from open source projects.

1. SystemLib#addContact()

Project: Cafe
Source File: SystemLib.java
View license
/**
     * add a contact
     * 
     * @param name
     *            : the contact's show name
     * @param phone
     *            : the contact's phone number
     * @return the uri string of the contact
     */
public String addContact(String name, String phone) {
    ContentValues values = new ContentValues();
    values.put(People.NAME, name);
    Uri contactUri = mContext.getContentResolver().insert(People.CONTENT_URI, values);
    Uri numberUri = Uri.withAppendedPath(contactUri, People.Phones.CONTENT_DIRECTORY);
    values.clear();
    values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE);
    values.put(People.NUMBER, phone);
    mContext.getContentResolver().insert(numberUri, values);
    return contactUri.toString();
}

2. TrayProviderTest#testDelete()

Project: tray
Source File: TrayProviderTest.java
View license
public void testDelete() throws Exception {
    final Uri[] workingUris = { mTrayUri.get(), mTrayUri.builder().setModule("module").build(), mTrayUri.builder().setModule("module").setKey("key").build(), mTrayUri.getInternal(), mTrayUri.builder().setInternal(true).setModule("module").build(), mTrayUri.builder().setInternal(true).setModule("module").setKey("key").build() };
    for (Uri uri : workingUris) {
        getProviderMockContext().getContentResolver().delete(uri, null, null);
    }
    final Uri badUri = Uri.withAppendedPath(Uri.parse("content://" + MockProvider.AUTHORITY), "something");
    try {
        getProviderMockContext().getContentResolver().delete(badUri, null, null);
        fail();
    } catch (IllegalArgumentException e) {
        assertTrue(e.getMessage().contains("not supported"));
    }
}

3. CropImageActivity#getOutputUri()

View license
/**
     * Get Android uri to save the cropped image into.<br>
     * Use the given in options or create a temp file.
     */
protected Uri getOutputUri() {
    Uri outputUri = mOptions.outputUri;
    if (outputUri.equals(Uri.EMPTY)) {
        try {
            String ext = mOptions.outputCompressFormat == Bitmap.CompressFormat.JPEG ? ".jpg" : mOptions.outputCompressFormat == Bitmap.CompressFormat.PNG ? ".png" : ".wepb";
            outputUri = Uri.fromFile(File.createTempFile("cropped", ext, getCacheDir()));
        } catch (IOException e) {
            throw new RuntimeException("Failed to create temp file for output image", e);
        }
    }
    return outputUri;
}

4. Helper#encodeUrl()

Project: Android-RTEditor
Source File: Helper.java
View license
/**
     * This method encodes the query part of an url
     * @param url an url (e.g. http://www.1gravity.com?query=üö)
     * @return The url with an encoded query, e.g. http://www.1gravity.com?query%3D%C3%BC%C3%B6
     */
public static String encodeUrl(String url) {
    Uri uri = Uri.parse(url);
    try {
        Map<String, List<String>> splitQuery = splitQuery(uri);
        StringBuilder encodedQuery = new StringBuilder();
        for (String key : splitQuery.keySet()) {
            for (String value : splitQuery.get(key)) {
                if (encodedQuery.length() > 0) {
                    encodedQuery.append("&");
                }
                encodedQuery.append(key + "=" + URLEncoder.encode(value, "UTF-8"));
            }
        }
        String queryString = encodedQuery != null && encodedQuery.length() > 0 ? "?" + encodedQuery : "";
        URI baseUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, uri.getFragment());
        return baseUri + queryString;
    } catch (UnsupportedEncodingException ignore) {
    } catch (URISyntaxException ignore) {
    }
    return uri.toString();
}

5. AudioUtils#writeAudioToMedia()

Project: android-utils
Source File: AudioUtils.java
View license
/**
	 * 
	 * @deprecated
	 * <br/>
	 * Use {@link nl.changer.android.opensource.AudioUtils#saveAudio(android.content.Context)}
	 * Insert an audio into {@link android.provider.MediaStore.Images.Media} content provider of the device.
	 * 
	 * @return The media content Uri to the newly created audio, or null if failed for any reason.
	 * ***/
public static Uri writeAudioToMedia(Context ctx, File audioFile) {
    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, audioFile.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, "");
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
    values.put(MediaStore.MediaColumns.SIZE, audioFile.length());
    values.put(MediaStore.Audio.Media.ARTIST, "");
    values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
    // Now set some extra features it depend on you
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
    values.put(MediaStore.Audio.Media.IS_ALARM, false);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(audioFile.getAbsolutePath());
    Uri uri2 = ctx.getContentResolver().insert(uri, values);
    if (uri2 == null || TextUtils.isEmpty(uri2.toString())) {
        Log.w(TAG, "Something went wrong while inserting data to content resolver");
    }
    return uri2;
}

6. AudioUtils#saveAudio()

Project: android-utils
Source File: AudioUtils.java
View license
/**
	 * 
	 * @param ctx
	 * @return The media content Uri to the newly created audio, or null if failed for any reason.
	 */
private static Uri saveAudio(Context ctx) {
    File audioFile = new File(mFileName);
    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, audioFile.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, "");
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
    values.put(MediaStore.MediaColumns.SIZE, audioFile.length());
    values.put(MediaStore.Audio.Media.ARTIST, "");
    values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
    // Now set some extra features it depend on you
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
    values.put(MediaStore.Audio.Media.IS_ALARM, false);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(audioFile.getAbsolutePath());
    Uri uri2 = ctx.getContentResolver().insert(uri, values);
    if (uri2 == null || TextUtils.isEmpty(uri2.toString())) {
        Log.w(TAG, "Something went wrong while inserting data to content resolver");
    }
    return uri2;
}

7. ContentProviderTest#testInsertField()

View license
/**
     * Check that inserting and removing a note into default deck works as expected
     */
public void testInsertField() throws Exception {
    // Get required objects for test
    final ContentResolver cr = getContext().getContentResolver();
    Collection col = CollectionHelper.getInstance().getCol(getContext());
    JSONObject model = Models.addBasicModel(col, BASIC_MODEL_NAME);
    long modelId = model.getLong("id");
    JSONArray initialFldsArr = model.getJSONArray("flds");
    int initialFieldCount = initialFldsArr.length();
    Uri noteTypeUri = ContentUris.withAppendedId(FlashCardsContract.Model.CONTENT_URI, modelId);
    ContentValues insertFieldValues = new ContentValues();
    insertFieldValues.put(FlashCardsContract.Model.FIELD_NAME, TEST_FIELD_NAME);
    Uri fieldUri = cr.insert(Uri.withAppendedPath(noteTypeUri, "fields"), insertFieldValues);
    assertNotNull("Check field uri", fieldUri);
    // Ensure that the changes are physically saved to the DB
    col = reopenCol();
    model = col.getModels().get(modelId);
    // Test the field is as expected
    long fieldId = ContentUris.parseId(fieldUri);
    assertEquals("Check field id", initialFieldCount, fieldId);
    JSONArray fldsArr = model.getJSONArray("flds");
    assertEquals("Check fields length", initialFieldCount + 1, fldsArr.length());
    assertEquals("Check last field name", TEST_FIELD_NAME, fldsArr.getJSONObject(fldsArr.length() - 1).optString("name", ""));
    col.getModels().rem(model);
}

8. AddContentApi#addNoteForContentValues()

Project: Anki-Android
Source File: AddContentApi.java
View license
private Uri addNoteForContentValues(long deckId, ContentValues values) {
    Uri newNoteUri = mResolver.insert(Note.CONTENT_URI, values);
    if (newNoteUri == null) {
        return null;
    }
    // Move cards to specified deck
    Uri cardsUri = Uri.withAppendedPath(newNoteUri, "cards");
    final Cursor cardsCursor = mResolver.query(cardsUri, null, null, null, null);
    if (cardsCursor == null) {
        return null;
    }
    try {
        while (cardsCursor.moveToNext()) {
            String ord = cardsCursor.getString(cardsCursor.getColumnIndex(Card.CARD_ORD));
            ContentValues cardValues = new ContentValues();
            cardValues.put(Card.DECK_ID, deckId);
            Uri cardUri = Uri.withAppendedPath(Uri.withAppendedPath(newNoteUri, "cards"), ord);
            mResolver.update(cardUri, cardValues, null, null);
        }
    } finally {
        cardsCursor.close();
    }
    return newNoteUri;
}

9. URLChecker#prepareURL()

Project: AntennaPod
Source File: URLChecker.java
View license
/**
     * Checks if URL is valid and modifies it if necessary.
     * This method also handles protocol relative URLs.
     *
     * @param url  The url which is going to be prepared
     * @param base The url against which the (possibly relative) url is applied. If this is null,
     *             the result of prepareURL(url) is returned instead.
     * @return The prepared url
     */
public static String prepareURL(String url, String base) {
    if (base == null) {
        return prepareURL(url);
    }
    url = url.trim();
    base = prepareURL(base);
    Uri urlUri = Uri.parse(url);
    Uri baseUri = Uri.parse(base);
    if (urlUri.isRelative() && baseUri.isAbsolute()) {
        return urlUri.buildUpon().scheme(baseUri.getScheme()).build().toString();
    } else {
        return prepareURL(url);
    }
}

10. AppSettingsActivity#loadData()

Project: apg
Source File: AppSettingsActivity.java
View license
private void loadData(Bundle savedInstanceState, Uri appUri) {
    mAppSettings = new ProviderHelper(this).getApiAppSettings(appUri);
    // get application name and icon from package manager
    String appName;
    Drawable appIcon = null;
    PackageManager pm = getApplicationContext().getPackageManager();
    try {
        ApplicationInfo ai = pm.getApplicationInfo(mAppSettings.getPackageName(), 0);
        appName = (String) pm.getApplicationLabel(ai);
        appIcon = pm.getApplicationIcon(ai);
    } catch (PackageManager.NameNotFoundException e) {
        appName = mAppSettings.getPackageName();
    }
    mAppNameView.setText(appName);
    mAppIconView.setImageDrawable(appIcon);
    Uri accountsUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ACCOUNTS).build();
    Log.d(Constants.TAG, "accountsUri: " + accountsUri);
    Uri allowedKeysUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ALLOWED_KEYS).build();
    Log.d(Constants.TAG, "allowedKeysUri: " + allowedKeysUri);
    startListFragments(savedInstanceState, accountsUri, allowedKeysUri);
}

11. ContactHelper#debugDeleteRawContacts()

Project: apg
Source File: ContactHelper.java
View license
/**
     * Delete all raw contacts associated to OpenKeychain, including those from "me" contact
     * defined by ContactsContract.Profile
     *
     * @return number of rows deleted
     */
private static int debugDeleteRawContacts(ContentResolver resolver) {
    // CALLER_IS_SYNCADAPTER allows us to actually wipe the RawContact from the device, otherwise
    // would be just flagged for deletion
    Uri deleteUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
    Log.d(Constants.TAG, "Deleting all raw contacts associated to OK...");
    int delete = resolver.delete(deleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[] { Constants.ACCOUNT_TYPE });
    Uri mainProfileDeleteUri = ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
    delete += resolver.delete(mainProfileDeleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[] { Constants.ACCOUNT_TYPE });
    return delete;
}

12. GCalHelper#rescheduleRepeatingTask()

Project: astrid
Source File: GCalHelper.java
View license
public static void rescheduleRepeatingTask(Task task, ContentResolver cr) {
    String taskUri = getTaskEventUri(task);
    if (TextUtils.isEmpty(taskUri))
        return;
    Uri eventUri = Uri.parse(taskUri);
    String calendarId = getCalendarId(eventUri, cr);
    if (calendarId == null) {
        // Bail out, no calendar id
        //$NON-NLS-1$
        task.setValue(Task.CALENDAR_URI, "");
        return;
    }
    ContentValues cv = new ContentValues();
    cv.put(CALENDAR_ID_COLUMN, calendarId);
    Uri uri = createTaskEvent(task, cr, cv, false);
    task.setValue(Task.CALENDAR_URI, uri.toString());
}

13. ImApp#deleteAccount()

Project: ChatSecureAndroid
Source File: ImApp.java
View license
public void deleteAccount(long accountId, long providerId) {
    ContentResolver resolver = getContentResolver();
    Uri accountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId);
    resolver.delete(accountUri, null, null);
    Uri providerUri = ContentUris.withAppendedId(Imps.Provider.CONTENT_URI, providerId);
    resolver.delete(providerUri, null, null);
    Uri.Builder builder = Imps.Contacts.CONTENT_URI_CONTACTS_BY.buildUpon();
    ContentUris.appendId(builder, providerId);
    ContentUris.appendId(builder, accountId);
    resolver.delete(builder.build(), null, null);
}

14. ChatSessionAdapter#onConvertToGroupChatSuccess()

View license
void onConvertToGroupChatSuccess(ChatGroup group) {
    Contact oldParticipant = (Contact) mChatSession.getParticipant();
    String oldAddress = getAddress();
    mChatSession.setParticipant(group);
    mChatSessionManager.updateChatSession(oldAddress, this);
    Uri oldChatUri = mChatURI;
    Uri oldMessageUri = mMessageURI;
    init(group, false);
    copyHistoryMessages(oldParticipant);
    mContentResolver.delete(oldMessageUri, NON_CHAT_MESSAGE_SELECTION, null);
    mContentResolver.delete(oldChatUri, null, null);
    mListenerAdapter.notifyChatSessionConverted();
    mConvertingToGroupChat = false;
}

15. SoundRecordingActivity#addRecordingToMediaLibrary()

View license
protected void addRecordingToMediaLibrary() {
    ContentValues values = new ContentValues(4);
    long current = System.currentTimeMillis();
    values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
    values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
    values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
    values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
    ContentResolver contentResolver = getContentResolver();
    Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Uri newUri = contentResolver.insert(base, values);
    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
    Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
}

16. Options#parseAssets()

View license
/**
     * Parse asset URIs.
     */
private void parseAssets() {
    if (options.has("iconUri") && !options.optBoolean("updated"))
        return;
    Uri iconUri = assets.parse(options.optString("icon", "res://icon"));
    Uri soundUri = assets.parseSound(options.optString("sound", null));
    try {
        options.put("iconUri", iconUri.toString());
        options.put("soundUri", soundUri.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

17. MessageUtils#lockMessage()

Project: qksms
Source File: MessageUtils.java
View license
public static void lockMessage(Context context, MessageItem msgItem, boolean locked) {
    Uri uri;
    if ("sms".equals(msgItem.mType)) {
        uri = Sms.CONTENT_URI;
    } else {
        uri = Mms.CONTENT_URI;
    }
    final Uri lockUri = ContentUris.withAppendedId(uri, msgItem.mMsgId);
    final ContentValues values = new ContentValues(1);
    values.put("locked", locked ? 1 : 0);
    new Thread(() -> {
        context.getContentResolver().update(lockUri, values, null, null);
    }, "MainActivity.lockMessage").start();
}

18. Transaction#createPartImage()

Project: qksms
Source File: Transaction.java
View license
// create the image part to be stored in database
private static Uri createPartImage(Context context, String id, byte[] imageBytes, String mimeType) throws Exception {
    ContentValues mmsPartValue = new ContentValues();
    mmsPartValue.put("mid", id);
    mmsPartValue.put("ct", mimeType);
    mmsPartValue.put("cid", "<" + System.currentTimeMillis() + ">");
    Uri partUri = Uri.parse("content://mms/" + id + "/part");
    Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
    // Add data to part
    OutputStream os = context.getContentResolver().openOutputStream(res);
    ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
    byte[] buffer = new byte[256];
    for (int len = 0; (len = is.read(buffer)) != -1; ) {
        os.write(buffer, 0, len);
    }
    os.close();
    is.close();
    return res;
}

19. PutResultTest#createInsertResult()

Project: storio
Source File: PutResultTest.java
View license
@Test
public void createInsertResult() {
    final Uri insertedUri = mock(Uri.class);
    final Uri affectedUri = mock(Uri.class);
    final PutResult insertResult = PutResult.newInsertResult(insertedUri, affectedUri);
    assertThat(insertResult.wasInserted()).isTrue();
    assertThat(insertResult.wasUpdated()).isFalse();
    assertThat(insertResult.wasNotInserted()).isFalse();
    assertThat(insertResult.wasNotUpdated()).isTrue();
    assertThat(insertResult.insertedUri()).isSameAs(insertedUri);
    assertThat(insertResult.affectedUri()).isSameAs(affectedUri);
    assertThat(insertResult.numberOfRowsUpdated()).isNull();
}

20. DeleteQueryTest#completeBuilderShouldUpdateUriObject()

Project: storio
Source File: DeleteQueryTest.java
View license
@Test
public void completeBuilderShouldUpdateUriObject() {
    Uri oldUri = mock(Uri.class);
    Uri newUri = mock(Uri.class);
    DeleteQuery query = DeleteQuery.builder().uri(oldUri).uri(newUri).build();
    assertThat(query.uri()).isSameAs(newUri);
}

21. InsertQueryTest#completeBuilderShouldUpdateUriObject()

Project: storio
Source File: InsertQueryTest.java
View license
@Test
public void completeBuilderShouldUpdateUriObject() {
    Uri oldUri = mock(Uri.class);
    Uri newUri = mock(Uri.class);
    InsertQuery query = InsertQuery.builder().uri(oldUri).uri(newUri).build();
    assertThat(query.uri()).isSameAs(newUri);
}

22. QueryTest#completeBuilderShouldUpdateUriObject()

Project: storio
Source File: QueryTest.java
View license
@Test
public void completeBuilderShouldUpdateUriObject() {
    Uri oldUri = mock(Uri.class);
    Uri newUri = mock(Uri.class);
    Query query = Query.builder().uri(oldUri).uri(newUri).build();
    assertThat(query.uri()).isSameAs(newUri);
}

23. UpdateQueryTest#completeBuilderShouldUpdateUriObject()

Project: storio
Source File: UpdateQueryTest.java
View license
@Test
public void completeBuilderShouldUpdateUriObject() {
    Uri oldUri = mock(Uri.class);
    Uri newUri = mock(Uri.class);
    UpdateQuery query = UpdateQuery.builder().uri(oldUri).uri(newUri).build();
    assertThat(query.uri()).isSameAs(newUri);
}

24. PhotoActivity#onCreate()

View license
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.de_ac_photo);
    mPhotoFragment = (PhotoFragment) getSupportFragmentManager().findFragmentById(R.id.photo_fragment);
    Uri uri = getIntent().getParcelableExtra("photo");
    Uri thumbUri = getIntent().getParcelableExtra("thumbnail");
    mUri = uri;
    if (uri != null)
        mPhotoFragment.initPhoto(uri, thumbUri, new PhotoFragment.PhotoDownloadListener() {

            @Override
            public void onDownloaded(Uri uri) {
                mDownloaded = uri;
            }

            @Override
            public void onDownloadError() {
            }
        });
}

25. LocalCover#buildCoverUrl()

Project: dmix
Source File: LocalCover.java
View license
public static String buildCoverUrl(String serverName, String musicPath, final String path, final String fileName) {
    if (musicPath.startsWith(URL_PREFIX)) {
        int hostPortEnd = musicPath.indexOf(URL_PREFIX.length(), '/');
        if (hostPortEnd == -1) {
            hostPortEnd = musicPath.length();
        }
        serverName = musicPath.substring(URL_PREFIX.length(), hostPortEnd);
        musicPath = musicPath.substring(hostPortEnd);
    }
    final Uri.Builder uriBuilder = Uri.parse(URL_PREFIX + serverName).buildUpon();
    appendPathString(uriBuilder, musicPath);
    appendPathString(uriBuilder, path);
    appendPathString(uriBuilder, fileName);
    final Uri uri = uriBuilder.build();
    return uri.toString();
}

26. AppSettingsActivity#loadData()

View license
private void loadData(Bundle savedInstanceState, Uri appUri) {
    mAppSettings = new ApiDataAccessObject(this).getApiAppSettings(appUri);
    // get application name and icon from package manager
    String appName;
    Drawable appIcon = null;
    PackageManager pm = getApplicationContext().getPackageManager();
    try {
        ApplicationInfo ai = pm.getApplicationInfo(mAppSettings.getPackageName(), 0);
        appName = (String) pm.getApplicationLabel(ai);
        appIcon = pm.getApplicationIcon(ai);
    } catch (PackageManager.NameNotFoundException e) {
        appName = mAppSettings.getPackageName();
    }
    mAppNameView.setText(appName);
    mAppIconView.setImageDrawable(appIcon);
    Uri accountsUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ACCOUNTS).build();
    Log.d(Constants.TAG, "accountsUri: " + accountsUri);
    Uri allowedKeysUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ALLOWED_KEYS).build();
    Log.d(Constants.TAG, "allowedKeysUri: " + allowedKeysUri);
    startListFragments(savedInstanceState, accountsUri, allowedKeysUri);
}

27. ContactHelper#deleteAllContacts()

Project: open-keychain
Source File: ContactHelper.java
View license
/**
     * Delete all raw contacts associated to OpenKeychain, including those from "me" contact
     * defined by ContactsContract.Profile
     *
     * @return number of rows deleted
     */
public int deleteAllContacts() {
    // CALLER_IS_SYNCADAPTER allows us to actually wipe the RawContact from the device, otherwise
    // would be just flagged for deletion
    Uri deleteUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
    Log.d(Constants.TAG, "Deleting all raw contacts associated to OK...");
    int delete = mContentResolver.delete(deleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[] { Constants.ACCOUNT_TYPE });
    Uri mainProfileDeleteUri = ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
    delete += mContentResolver.delete(mainProfileDeleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[] { Constants.ACCOUNT_TYPE });
    return delete;
}

28. AlarmReceiver#buildPath()

View license
public String buildPath(Context context) {
    SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String arch = mySharedPreferences.getString("prefArch", "arm64");
    String base = mySharedPreferences.getString("prefBase", "").trim();
    Uri builtUri = Uri.parse(base).buildUpon().appendPath("opengapps").appendPath(arch).appendPath("releases").build();
    return builtUri.toString();
}

29. MainActivity#buildPath()

View license
public String buildPath(Context context) {
    SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String arch = mySharedPreferences.getString("prefArch", "arm64");
    String base = mySharedPreferences.getString("prefBase", getString(R.string.base_val)).trim();
    Uri builtUri = Uri.parse(base).buildUpon().appendPath(getString(R.string.subdir)).appendPath(arch).appendPath("releases").build();
    return builtUri.toString();
}

30. LabelProviderTest#testInsert_success()

Project: talkback
Source File: LabelProviderTest.java
View license
/**
     * Tests {@link com.android.talkback.labeling.LabelProvider#insert(android.net.Uri, android.content.ContentValues)} with valid content
     * values.
     */
@SmallTest
public void testInsert_success() throws RemoteException {
    final ContentProviderClient client = getContentProviderClient();
    final ContentValues contentValues = getValidLabelContentValues();
    final Uri resultUri;
    try {
        resultUri = client.insert(LabelProvider.LABELS_CONTENT_URI, contentValues);
    } finally {
        client.release();
    }
    final Uri expectedUri = ContentUris.withAppendedId(LabelProvider.LABELS_CONTENT_URI, 1L);
    assertEquals(expectedUri, resultUri);
}

31. PmDetailAdapter#handlerSpan()

Project: TLint
Source File: PmDetailAdapter.java
View license
private void handlerSpan(URLSpan span) {
    String url = span.getURL();
    if (TextUtils.isEmpty(url)) {
        return;
    }
    Uri uri = Uri.parse(url);
    switch(uri.getScheme()) {
        case "kanqiu":
            if (url.contains("topic")) {
                String tid = uri.getLastPathSegment();
                ContentActivity.startActivity(mActivity, "", tid, "", 1);
            } else if (url.contains("board")) {
                String boardId = uri.getLastPathSegment();
                ThreadListActivity.startActivity(mActivity, boardId);
            }
            break;
        case "app":
            break;
        case "http":
        case "https":
            BrowserActivity.startActivity(mActivity, url);
            break;
    }
}

32. TrayProviderTest#assertInsertUriEqualsNullForUpdateOrInsertError()

Project: tray
Source File: TrayProviderTest.java
View license
void assertInsertUriEqualsNullForUpdateOrInsertError(final int errorCode) {
    final TrayContentProvider trayContentProvider = new TrayContentProvider();
    final TrayContentProvider spy = spy(trayContentProvider);
    final Uri mockInsertUri = mTrayUri.builder().setModule("module").setKey("key").build();
    doReturn(null).when(spy).getWritableDatabase(mockInsertUri);
    doReturn(errorCode).when(spy).insertOrUpdate(any(SQLiteDatabase.class), anyString(), anyString(), any(String[].class), any(ContentValues.class), any(String[].class));
    final Uri insert = spy.insert(mockInsertUri, new ContentValues());
    assertNull(insert);
}

33. Options#parseAssets()

Project: VallasciApp-ionic
Source File: Options.java
View license
/**
     * Parse asset URIs.
     */
private void parseAssets() {
    if (options.has("iconUri") && !options.optBoolean("updated"))
        return;
    Uri iconUri = assets.parse(options.optString("icon", "icon"));
    Uri soundUri = assets.parseSound(options.optString("sound", null));
    try {
        options.put("iconUri", iconUri.toString());
        options.put("soundUri", soundUri.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

34. UIUtils#tryTranslateHttpIntent()

Project: iosched
Source File: UIUtils.java
View license
/**
     * If an activity's intent is for a Google I/O web URL that the app can handle
     * natively, this method translates the intent to the equivalent native intent.
     */
public static void tryTranslateHttpIntent(Activity activity) {
    Intent intent = activity.getIntent();
    if (intent == null) {
        return;
    }
    Uri uri = intent.getData();
    if (uri == null || TextUtils.isEmpty(uri.getPath())) {
        return;
    }
    Uri sessionDetailWebUrlPrefix = Uri.parse(Config.SESSION_DETAIL_WEB_URL_PREFIX);
    String prefixPath = sessionDetailWebUrlPrefix.getPath();
    String path = uri.getPath();
    if (sessionDetailWebUrlPrefix.getScheme().equals(uri.getScheme()) && sessionDetailWebUrlPrefix.getHost().equals(uri.getHost()) && path.startsWith(prefixPath)) {
        String sessionId = path.substring(prefixPath.length());
        activity.setIntent(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId)));
    }
}

35. ContactHelper#openDisplayPhoto()

View license
/**
     * Get the InputStream object of the contact photo with given contact ID.
     *
     * @param context       Context object of the caller.
     * @param contactId     Contact ID.
     * @return              InputStream object of the contact photo.
     */
public static InputStream openDisplayPhoto(Context context, long contactId) {
    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
    Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
    try {
        AssetFileDescriptor fd = context.getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
        return fd.createInputStream();
    } catch (IOException e) {
        return null;
    }
}

36. ShadowsocksConfig#parse()

Project: SmartZPN
Source File: ShadowsocksConfig.java
View license
public static ShadowsocksConfig parse(String proxyInfo) throws Exception {
    ShadowsocksConfig config = new ShadowsocksConfig();
    Uri uri = Uri.parse(proxyInfo);
    if (uri.getPort() == -1) {
        String base64String = uri.getHost();
        proxyInfo = "ss://" + new String(Base64.decode(base64String.getBytes("ASCII"), Base64.DEFAULT));
        uri = Uri.parse(proxyInfo);
    }
    String userInfoString = uri.getUserInfo();
    if (userInfoString != null) {
        String[] userStrings = userInfoString.split(":");
        config.EncryptMethod = userStrings[0];
        if (userStrings.length >= 2) {
            config.Password = userStrings[1];
        }
    }
    config.ServerAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    config.Encryptor = EncryptorFactory.createEncryptorByConfig(config);
    return config;
}

37. ConversationActivity#extractUriFromIntent()

View license
@SuppressLint("NewApi")
private static List<Uri> extractUriFromIntent(final Intent intent) {
    List<Uri> uris = new ArrayList<>();
    if (intent == null) {
        return uris;
    }
    Uri uri = intent.getData();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
        ClipData clipData = intent.getClipData();
        for (int i = 0; i < clipData.getItemCount(); ++i) {
            uris.add(clipData.getItemAt(i).getUri());
        }
    } else {
        uris.add(uri);
    }
    return uris;
}

38. HttpConnectConfig#parse()

Project: SmartZPN
Source File: HttpConnectConfig.java
View license
public static HttpConnectConfig parse(String proxyInfo) {
    HttpConnectConfig config = new HttpConnectConfig();
    Uri uri = Uri.parse(proxyInfo);
    String userInfoString = uri.getUserInfo();
    if (userInfoString != null) {
        String[] userStrings = userInfoString.split(":");
        config.UserName = userStrings[0];
        if (userStrings.length >= 2) {
            config.Password = userStrings[1];
        }
    }
    config.ServerAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    return config;
}

39. ShadowsocksConfig#parse()

Project: SmartProxy
Source File: ShadowsocksConfig.java
View license
public static ShadowsocksConfig parse(String proxyInfo) throws Exception {
    ShadowsocksConfig config = new ShadowsocksConfig();
    Uri uri = Uri.parse(proxyInfo);
    if (uri.getPort() == -1) {
        String base64String = uri.getHost();
        proxyInfo = "ss://" + new String(Base64.decode(base64String.getBytes("ASCII"), Base64.DEFAULT));
        uri = Uri.parse(proxyInfo);
    }
    String userInfoString = uri.getUserInfo();
    if (userInfoString != null) {
        String[] userStrings = userInfoString.split(":");
        config.EncryptMethod = userStrings[0];
        if (userStrings.length >= 2) {
            config.Password = userStrings[1];
        }
    }
    config.ServerAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    config.Encryptor = EncryptorFactory.createEncryptorByConfig(config);
    return config;
}

40. HttpConnectConfig#parse()

Project: SmartProxy
Source File: HttpConnectConfig.java
View license
public static HttpConnectConfig parse(String proxyInfo) {
    HttpConnectConfig config = new HttpConnectConfig();
    Uri uri = Uri.parse(proxyInfo);
    String userInfoString = uri.getUserInfo();
    if (userInfoString != null) {
        String[] userStrings = userInfoString.split(":");
        config.UserName = userStrings[0];
        if (userStrings.length >= 2) {
            config.Password = userStrings[1];
        }
    }
    config.ServerAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    return config;
}

41. MainActivity#onCreate()

Project: Small
Source File: MainActivity.java
View license
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        System.out.println("savedInstanceState: " + savedInstanceState);
    }
    setContentView(R.layout.activity_main);
    setTitle("Detail");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    Uri uri = Small.getUri(this);
    if (uri != null) {
        String from = uri.getQueryParameter("from");
        if (from != null) {
            TextView tvFrom = (TextView) findViewById(R.id.tvFrom);
            tvFrom.setText("-- Greet from " + from);
        }
    }
}

42. PickerFragment#listItemAction()

Project: SimpleExplorer
Source File: PickerFragment.java
View license
@Override
public void listItemAction(File file) {
    final Uri pickedUri = FileProvider.getUriForFile(getActivity(), "com.dnielfe.manager.fileprovider", file);
    final Intent result = new Intent();
    result.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    result.setData(pickedUri);
    final Activity activity = getActivity();
    activity.setResult(Activity.RESULT_OK, result);
    activity.finish();
}

43. ResultActivity#onCreate()

Project: SimpleCropView
Source File: ResultActivity.java
View license
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    // apply custom font
    FontUtils.setFont((ViewGroup) findViewById(R.id.layout_root));
    mImageView = (ImageView) findViewById(R.id.result_image);
    mExecutor = Executors.newSingleThreadExecutor();
    final Uri uri = getIntent().getData();
    mExecutor.submit(new LoadScaledImageTask(this, uri, mImageView, calcImageSize()));
}

44. ShareActivity#initializeMedia()

Project: Silence
Source File: ShareActivity.java
View license
private void initializeMedia() {
    final Context context = this;
    isPassingAlongMedia = false;
    Uri streamExtra = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
    mimeType = getMimeType(streamExtra);
    if (streamExtra != null && PartAuthority.isLocalUri(streamExtra)) {
        isPassingAlongMedia = true;
        resolvedExtra = streamExtra;
        fragmentContainer.setVisibility(View.VISIBLE);
        progressWheel.setVisibility(View.GONE);
    } else {
        fragmentContainer.setVisibility(View.GONE);
        progressWheel.setVisibility(View.VISIBLE);
        new ResolveMediaTask(context).execute(streamExtra);
    }
}

45. RecipientProvider#getIndividualRecipientDetails()

Project: Silence
Source File: RecipientProvider.java
View license
@NonNull
private RecipientDetails getIndividualRecipientDetails(Context context, long recipientId, @NonNull String number) {
    Optional<RecipientsPreferences> preferences = DatabaseFactory.getRecipientPreferenceDatabase(context).getRecipientsPreferences(new long[] { recipientId });
    MaterialColor color = preferences.isPresent() ? preferences.get().getColor() : null;
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    Cursor cursor = context.getContentResolver().query(uri, CALLER_ID_PROJECTION, null, null, null);
    try {
        if (cursor != null && cursor.moveToFirst()) {
            Uri contactUri = Contacts.getLookupUri(cursor.getLong(2), cursor.getString(1));
            String name = cursor.getString(3).equals(cursor.getString(0)) ? null : cursor.getString(0);
            ContactPhoto contactPhoto = ContactPhotoFactory.getContactPhoto(context, Uri.withAppendedPath(Contacts.CONTENT_URI, cursor.getLong(2) + ""), name);
            return new RecipientDetails(cursor.getString(0), cursor.getString(3), contactUri, contactPhoto, color);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    if (STATIC_DETAILS.containsKey(number))
        return STATIC_DETAILS.get(number);
    else
        return new RecipientDetails(null, number, null, ContactPhotoFactory.getDefaultContactPhoto(null), color);
}

46. SingleRecipientNotificationBuilder#hasBigPictureSlide()

View license
private boolean hasBigPictureSlide(@Nullable SlideDeck slideDeck) {
    if (masterSecret == null || slideDeck == null || Build.VERSION.SDK_INT < 16) {
        return false;
    }
    Slide thumbnailSlide = slideDeck.getThumbnailSlide();
    if (thumbnailSlide == null)
        return false;
    Uri uri = thumbnailSlide.getThumbnailUri();
    if (uri == null)
        return false;
    DecryptableStreamUriLoader.DecryptableUri decryptableUri = new DecryptableStreamUriLoader.DecryptableUri(masterSecret, uri);
    return decryptableUri != null && thumbnailSlide.hasImage() && !thumbnailSlide.isInProgress();
}

47. SmsMigrator#getTheirCanonicalAddress()

Project: Silence
Source File: SmsMigrator.java
View license
private static String getTheirCanonicalAddress(Context context, String theirRecipientId) {
    Uri uri = Uri.parse("content://mms-sms/canonical-address/" + theirRecipientId);
    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            return cursor.getString(0);
        } else {
            return null;
        }
    } catch (IllegalStateException iae) {
        Log.w("SmsMigrator", iae);
        return null;
    } finally {
        if (cursor != null)
            cursor.close();
    }
}

48. MmsDatabase#getCarrierMmsInformation()

Project: Silence
Source File: MmsDatabase.java
View license
public Cursor getCarrierMmsInformation(String apn) {
    Uri uri = Uri.withAppendedPath(Uri.parse("content://telephony/carriers"), "current");
    String selection = TextUtils.isEmpty(apn) ? null : "apn = ?";
    String[] selectionArgs = TextUtils.isEmpty(apn) ? null : new String[] { apn.trim() };
    try {
        return context.getContentResolver().query(uri, null, selection, selectionArgs, null);
    } catch (NullPointerException npe) {
        throw new IllegalArgumentException(npe);
    }
}

49. ConversationActivity#initializeDraft()

Project: Silence
Source File: ConversationActivity.java
View license
///// Initializers
private void initializeDraft() {
    final String draftText = getIntent().getStringExtra(TEXT_EXTRA);
    final Uri draftMedia = getIntent().getData();
    final MediaType draftMediaType = MediaType.from(getIntent().getType());
    if (draftText != null)
        composeText.setText(draftText);
    if (draftMedia != null && draftMediaType != null)
        setMedia(draftMedia, draftMediaType);
    if (draftText == null && draftMedia == null && draftMediaType == null) {
        initializeDraftFromDatabase();
    } else {
        updateToggleButtonState();
    }
}

50. SocialShareTest#videoMime()

Project: shelly
Source File: SocialShareTest.java
View license
@Test
public void videoMime() {
    Context currentContext = mock(Context.class);
    ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class);
    Uri mockUri = mock(Uri.class);
    Shelly.share(currentContext).video(mockUri).send();
    verify(currentContext).startActivity(argument.capture());
    Intent result = argument.getValue();
    assertEquals("video/*", result.getType());
}

51. SocialShareTest#imageMime()

Project: shelly
Source File: SocialShareTest.java
View license
@Test
public void imageMime() {
    Context currentContext = mock(Context.class);
    ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class);
    Uri mockUri = mock(Uri.class);
    Shelly.share(currentContext).image(mockUri).send();
    verify(currentContext).startActivity(argument.capture());
    Intent result = argument.getValue();
    assertEquals("image/*", result.getType());
}

52. CubeMapFragment#onActivityResult()

Project: ShaderEditor
Source File: CubeMapFragment.java
View license
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri imageUri;
    if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK && (imageUri = data.getData()) != null)
        cubeMapView.setSelectedFaceImage(imageUri);
}

53. AddUniformActivity#startActivityForIntent()

View license
private void startActivityForIntent(Intent intent) {
    if (intent == null)
        return;
    String type;
    if (!Intent.ACTION_SEND.equals(intent.getAction()) || (type = intent.getType()) == null || !type.startsWith("image/"))
        return;
    Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri == null)
        return;
    startActivity(CropImageActivity.getIntentForImage(this, imageUri));
}

54. MovieTools#addMovieWatchedShell()

Project: SeriesGuide
Source File: MovieTools.java
View license
/**
     * Inserts a movie shell into the database only holding TMDB id, list and watched states.
     */
private static boolean addMovieWatchedShell(Context context, int movieTmdbId) {
    ContentValues values = new ContentValues();
    values.put(SeriesGuideContract.Movies.TMDB_ID, movieTmdbId);
    values.put(SeriesGuideContract.Movies.IN_COLLECTION, false);
    values.put(SeriesGuideContract.Movies.IN_WATCHLIST, false);
    values.put(SeriesGuideContract.Movies.WATCHED, true);
    Uri insert = context.getContentResolver().insert(SeriesGuideContract.Movies.CONTENT_URI, values);
    return insert != null;
}

55. SeriesGuideProvider#insert()

View license
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
    Uri newItemUri;
    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    if (!applyingBatch()) {
        db.beginTransaction();
        try {
            newItemUri = insertInTransaction(db, uri, values);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } else {
        newItemUri = insertInTransaction(db, uri, values);
    }
    if (newItemUri != null) {
        //noinspection ConstantConditions
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return newItemUri;
}

56. Sentry#createXSentryAuthHeader()

Project: Sentry-Android
Source File: Sentry.java
View license
private static String createXSentryAuthHeader() {
    String header = "";
    Uri uri = Uri.parse(Sentry.getInstance().dsn);
    String authority = uri.getAuthority().replace("@" + uri.getHost(), "");
    String[] authorityParts = authority.split(":");
    String publicKey = authorityParts[0];
    String secretKey = authorityParts[1];
    header += "Sentry sentry_version=" + sentryVersion + ",";
    header += "sentry_client=sentry-android/" + VERSION + ",";
    header += "sentry_timestamp=" + System.currentTimeMillis() + ",";
    header += "sentry_key=" + publicKey + ",";
    header += "sentry_secret=" + secretKey;
    return header;
}

57. Sentry#init()

Project: Sentry-Android
Source File: Sentry.java
View license
public static void init(Context context, String dsn) {
    Sentry.getInstance().context = context.getApplicationContext();
    Uri uri = Uri.parse(dsn);
    String port = "";
    if (uri.getPort() >= 0) {
        port = ":" + uri.getPort();
    }
    Sentry.getInstance().baseUrl = uri.getScheme() + "://" + uri.getHost() + port;
    Sentry.getInstance().dsn = dsn;
    Sentry.getInstance().packageName = context.getPackageName();
    Sentry.getInstance().verifySsl = getVerifySsl(dsn);
    Sentry.getInstance().setupUncaughtExceptionHandler();
}

58. SearchActivity#doSearch()

Project: search-samples
Source File: SearchActivity.java
View license
private void doSearch(String query) {
    Uri searchUri = RecipeContentProvider.CONTENT_URI.buildUpon().appendPath("search").appendEncodedPath(query).build();
    String[] projection = { RecipeTable.ID, RecipeTable.TITLE, RecipeTable.DESCRIPTION, RecipeTable.PHOTO, RecipeTable.PREP_TIME };
    Cursor cursor = getContentResolver().query(searchUri, projection, null, null, null);
    cursor.moveToFirst();
    mAdapter.clearResults();
    while (!cursor.isAfterLast()) {
        final Recipe recipe = Recipe.fromCursor(cursor);
        mAdapter.addResult(recipe);
        cursor.moveToNext();
    }
}

59. DownloadPreferencesDelegateImpl#setupAboutHandlers()

View license
private void setupAboutHandlers() {
    final Uri uri = mPackageHelper.getMarketUri();
    final Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, uri);
    mPreferenceManager.findPreference(ApplicationPreferences.KEY_RATE_APP).setIntent(rateAppIntent);
    final Intent aboutIntent = new Intent(mContext, AboutActivity.class);
    mPreferenceManager.findPreference(ApplicationPreferences.KEY_ABOUT_ME).setIntent(aboutIntent);
    final Intent donateIntent = new Intent(mContext, BuyAdFreeActivity.class);
    final Preference donatePreference = mPreferenceManager.findPreference(ApplicationPreferences.KEY_DONATE);
    if (Config.Features.NEW_DONATE) {
        throw new IllegalStateException("New Donate isn't implemented yet, doh!");
    } else {
        donatePreference.setIntent(donateIntent);
        donatePreference.setTitle(mContext.getString(R.string.remove_ads));
        donatePreference.setEnabled(!mAppPreferences.isAdFree());
    }
}

60. TrackDownloaderImpl#setRequestStorage()

Project: scdl
Source File: TrackDownloaderImpl.java
View license
private void setRequestStorage(final Request request) throws IOException {
    final StorageType type = mPreferences.getStorageType();
    final File typePath = mPreferences.getStorageDirectory();
    String filename = mTrack.getDownloadFilename();
    if (type == StorageType.LOCAL) {
        filename += Config.TMP_DOWNLOAD_POSTFIX;
    }
    // have been removed in the meantime, so we rather double-check.
    if (!checkAndCreateTypePath(typePath)) {
        throw new IOException(String.format("Can't open directory %s to write.", typePath.toString()));
    }
    final Uri destinationUri = Uri.withAppendedPath(Uri.fromFile(typePath), filename);
    Ln.d("Local destination URI: %s", destinationUri.toString());
    request.setDestinationUri(destinationUri);
}

61. MainActivity#onNewIntent()

Project: sbt-android
Source File: MainActivity.java
View license
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Uri data = intent.getData();
    if (data == null)
        return;
    if ("u2020".equals(data.getScheme())) {
        Intent serviceIntent = new Intent(this, OauthService.class);
        serviceIntent.setData(data);
        startService(serviceIntent);
    }
}

62. ShareDribbbleImageTask#onPostExecute()

View license
@Override
protected void onPostExecute(File result) {
    if (result == null) {
        return;
    }
    // glide cache uses an unfriendly & extension-less name,
    // massage it based on the original
    String fileName = shot.images.best();
    fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
    File renamed = new File(result.getParent(), fileName);
    result.renameTo(renamed);
    Uri uri = FileProvider.getUriForFile(activity, activity.getString(R.string.share_authority), renamed);
    ShareCompat.IntentBuilder.from(activity).setText(getShareText()).setType(getImageMimeType(fileName)).setStream(uri).startChooser();
}

63. SalesforceWebViewClientHelper#isLoginRedirect()

View license
/**
     * Login redirect are of the form https://host/?ec=30x&startURL=xyz
     * @param url
     * @return null if this is not a login redirect and return the the value for startURL if this is a login redirect
     */
private static String isLoginRedirect(String url) {
    final Uri uri = Uri.parse(url);
    final Map<String, String> params = UriFragmentParser.parse(uri);
    final String ec = params.get("ec");
    int ecInt = (ec != null ? Integer.parseInt(ec) : -1);
    final String startURL = params.get("startURL");
    if ((ecInt == HttpStatus.SC_MOVED_PERMANENTLY || ecInt == HttpStatus.SC_MOVED_TEMPORARILY) && startURL != null) {
        return startURL;
    } else {
        return null;
    }
}

64. UriTest#shouldParseUris()

Project: robolectric
Source File: UriTest.java
View license
@Test
public void shouldParseUris() throws Exception {
    Uri testUri = Uri.parse("http://someplace.com:8080/a/path?param=value&another_param=another_value#top");
    assertThat(testUri.getQuery(), equalTo("param=value&another_param=another_value"));
    assertThat(testUri.getPort(), equalTo(8080));
    assertThat(testUri.getAuthority(), equalTo("someplace.com:8080"));
    assertThat(testUri.getHost(), equalTo("someplace.com"));
    assertThat(testUri.getFragment(), equalTo("top"));
    assertThat(testUri.getPath(), equalTo("/a/path"));
    assertThat(testUri.getScheme(), equalTo("http"));
}

65. MyImageDownloader#getStreamFromContent()

View license
/**
	 * Retrieves {@link java.io.InputStream} of image by URI (image is accessed using {@link android.content.ContentResolver}).
	 *
	 * @param imageUri Image URI
	 * @param extra    Auxiliary object which was passed to {@link com.nostra13.universalimageloader.core.DisplayImageOptions.Builder#extraForDownloader(Object)
	 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
	 * @return {@link java.io.InputStream} of image
	 * @throws java.io.FileNotFoundException if the provided URI could not be opened
	 */
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
    ContentResolver res = context.getContentResolver();
    Uri uri = Uri.parse(imageUri);
    if (// video thumbnail
    isVideoUri(uri)) {
        Long origId = Long.valueOf(uri.getLastPathSegment());
        Bitmap bitmap = MediaStore.Video.Thumbnails.getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null);
        if (bitmap != null) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 0, bos);
            return new ByteArrayInputStream(bos.toByteArray());
        }
    } else if (// contacts photo
    imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) {
        return ContactsContract.Contacts.openContactPhotoInputStream(res, uri, true);
    }
    return res.openInputStream(uri);
}

66. AsyncSocketMiddleware#nextConnection()

View license
private void nextConnection(AsyncHttpRequest request) {
    Uri uri = request.getUri();
    final int port = getSchemePort(uri);
    String key = computeLookup(uri, port, request.getProxyHost(), request.getProxyPort());
    synchronized (AsyncSocketMiddleware.this) {
        ConnectionInfo info = connectionInfo.get(key);
        if (info == null)
            return;
        --info.openCount;
        while (info.openCount < maxConnectionCount && info.queue.size() > 0) {
            GetSocketData gsd = info.queue.remove();
            SimpleCancellable socketCancellable = (SimpleCancellable) gsd.socketCancellable;
            if (socketCancellable.isCancelled())
                continue;
            Cancellable connect = getSocket(gsd);
            socketCancellable.setParent(connect);
        }
        maybeCleanupConnectionInfo(key);
    }
}

67. AsyncSocketMiddleware#recycleSocket()

View license
private void recycleSocket(final AsyncSocket socket, AsyncHttpRequest request) {
    if (socket == null)
        return;
    Uri uri = request.getUri();
    int port = getSchemePort(uri);
    final String lookup = computeLookup(uri, port, request.getProxyHost(), request.getProxyPort());
    final ArrayDeque<IdleSocketHolder> sockets;
    final IdleSocketHolder idleSocketHolder = new IdleSocketHolder(socket);
    synchronized (AsyncSocketMiddleware.this) {
        ConnectionInfo info = getOrCreateConnectionInfo(lookup);
        sockets = info.sockets;
        sockets.push(idleSocketHolder);
    }
    socket.setClosedCallback(new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            synchronized (AsyncSocketMiddleware.this) {
                sockets.remove(idleSocketHolder);
                maybeCleanupConnectionInfo(lookup);
            }
        }
    });
}

68. LinkDispatchActivity#onCreate()

Project: RedReader
Source File: LinkDispatchActivity.java
View license
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Intent intent = getIntent();
    if (intent == null) {
        Log.e(TAG, "Got null intent");
        finish();
        return;
    }
    final Uri data = intent.getData();
    if (data == null) {
        Log.e(TAG, "Got null intent data");
        finish();
        return;
    }
    LinkHandler.onLinkClicked(this, data.toString(), false, null, null, 0, true);
    finish();
}

69. SipConfigManager#getPreferenceIntegerValue()

Project: CSipSimple
Source File: SipConfigManager.java
View license
/**
     * Helper method to retrieve a csipsimple float config value
     * 
     * @param ctxt The context of your app
     * @param key the key for the setting you want to get
     * @param defaultValue the value you want to return if nothing found
     * @return the preference value
     */
public static Integer getPreferenceIntegerValue(Context ctxt, String key, Integer defaultValue) {
    Integer value = defaultValue;
    Uri uri = getPrefUriForKey(key);
    Cursor c = ctxt.getContentResolver().query(uri, null, Integer.class.getName(), null, null);
    if (c != null) {
        c.moveToFirst();
        Integer iValue = c.getInt(1);
        if (iValue != null) {
            value = iValue;
        }
        c.close();
    }
    return value;
}

70. OldLyricContentProvider#insert()

View license
@Override
public Uri insert(Uri uri, ContentValues values) {
    Uri ret = null;
    // Assert correct uri
    if (sURIMatcher.match(uri) != Constants.LYRIC_DIR) {
        throw new IllegalArgumentException("Illegal uri: " + uri);
    }
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    long rowId = db.insertWithOnConflict(Constants.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
    // Was insert successful?
    if (rowId != -1) {
        ret = ContentUris.withAppendedId(uri, rowId);
        LogUtils.i(TAG, "inserted uri: " + ret);
        // Notify that data for this uri has changed
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return ret;
}

71. FileHelper#getMimeType()

View license
/**
     * Returns the mime type of the data specified by the given URI string.
     *
     * @param uriString the URI string of the data
     * @return the mime type of the specified data
     */
public static String getMimeType(String uriString, CordovaInterface cordova) {
    String mimeType = null;
    Uri uri = Uri.parse(uriString);
    if (uriString.startsWith("content://")) {
        mimeType = cordova.getActivity().getContentResolver().getType(uri);
    } else {
        mimeType = getMimeTypeForExtension(uri.getPath());
    }
    return mimeType;
}

72. Whitelist#isUrlWhiteListed()

View license
public boolean isUrlWhiteListed(String uri) {
    if (whiteList == null)
        return true;
    Uri parsedUri = Uri.parse(uri);
    // Look for match in white list
    Iterator<URLPattern> pit = whiteList.iterator();
    while (pit.hasNext()) {
        URLPattern p = pit.next();
        if (p.matches(parsedUri)) {
            return true;
        }
    }
    return false;
}

73. Whitelist#isUrlWhiteListed()

Project: cordova-android
Source File: Whitelist.java
View license
public boolean isUrlWhiteListed(String uri) {
    if (whiteList == null)
        return true;
    Uri parsedUri = Uri.parse(uri);
    // Look for match in white list
    Iterator<URLPattern> pit = whiteList.iterator();
    while (pit.hasNext()) {
        URLPattern p = pit.next();
        if (p.matches(parsedUri)) {
            return true;
        }
    }
    return false;
}

74. CameraLauncher#getUriFromMediaStore()

View license
/**
     * Create entry in media store for image
     *
     * @return uri
     */
private Uri getUriFromMediaStore() {
    ContentValues values = new ContentValues();
    values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    Uri uri;
    try {
        uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    } catch (UnsupportedOperationException e) {
        LOG.d(LOG_TAG, "Can't write to external media storage.");
        try {
            uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
        } catch (UnsupportedOperationException ex) {
            LOG.d(LOG_TAG, "Can't write to internal media storage.");
            return null;
        }
    }
    return uri;
}

75. CameraLauncher#checkForDuplicateImage()

View license
/**
     * Used to find out if we are in a situation where the Camera Intent adds to images
     * to the content store. If we are using a FILE_URI and the number of images in the DB
     * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
     *
     * @param type FILE_URI or DATA_URL
     */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();
    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }
    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
    }
}

76. Capture#checkForDuplicateImage()

View license
/**
     * Used to find out if we are in a situation where the Camera Intent adds to images
     * to the content store.
     */
private void checkForDuplicateImage() {
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();
    // delete the duplicate file if the difference is 2
    if ((currentNumOfImages - numPics) == 2) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
    }
}

77. FileHelper#getMimeType()

View license
/**
     * Returns the mime type of the data specified by the given URI string.
     *
     * @param uriString the URI string of the data
     * @return the mime type of the specified data
     */
public static String getMimeType(String uriString, CordovaInterface cordova) {
    String mimeType = null;
    Uri uri = Uri.parse(uriString);
    if (uriString.startsWith("content://")) {
        mimeType = cordova.getActivity().getContentResolver().getType(uri);
    } else {
        // MimeTypeMap.getFileExtensionFromUrl() fails when there are query parameters.
        String extension = uri.getPath();
        int lastDot = extension.lastIndexOf('.');
        if (lastDot != -1) {
            extension = extension.substring(lastDot + 1);
        }
        // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
        extension = extension.toLowerCase();
        if (extension.equals("3ga")) {
            mimeType = "audio/3gpp";
        } else {
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
    }
    return mimeType;
}

78. Notification#beep()

View license
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
     * Beep plays the default notification ringtone.
     *
     * @param count     Number of times to play notification
     */
public void beep(long count) {
    Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone notification = RingtoneManager.getRingtone(this.cordova.getActivity().getBaseContext(), ringtone);
    // If phone is not set to silent mode
    if (notification != null) {
        for (long i = 0; i < count; ++i) {
            notification.play();
            long timeout = 5000;
            while (notification.isPlaying() && (timeout > 0)) {
                timeout = timeout - 100;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}

79. SimpleVideoStream#play()

View license
private void play() {
    mProgressBar.setVisibility(View.VISIBLE);
    Uri videoUri = Uri.parse(mVideoUrl);
    try {
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setVideoURI(videoUri);
        mMediaController = new MediaController(this);
        mMediaController.setAnchorView(mVideoView);
        mMediaController.setMediaPlayer(mVideoView);
        mVideoView.setMediaController(mMediaController);
    } catch (Throwable t) {
        Log.d(TAG, t.toString());
    }
}

80. FileHelper#getMimeType()

View license
/**
     * Returns the mime type of the data specified by the given URI string.
     *
     * @param uriString the URI string of the data
     * @return the mime type of the specified data
     */
public static String getMimeType(String uriString, CordovaInterface cordova) {
    String mimeType = null;
    Uri uri = Uri.parse(uriString);
    if (uriString.startsWith("content://")) {
        mimeType = cordova.getActivity().getContentResolver().getType(uri);
    } else {
        mimeType = getMimeTypeForExtension(uri.getPath());
    }
    return mimeType;
}

81. Whitelist#isUrlWhiteListed()

View license
public boolean isUrlWhiteListed(String uri) {
    if (whiteList == null)
        return true;
    Uri parsedUri = Uri.parse(uri);
    // Look for match in white list
    Iterator<URLPattern> pit = whiteList.iterator();
    while (pit.hasNext()) {
        URLPattern p = pit.next();
        if (p.matches(parsedUri)) {
            return true;
        }
    }
    return false;
}

82. SipConfigManager#getPreferenceStringValue()

Project: CSipSimple
Source File: SipConfigManager.java
View license
/**
     * Helper method to retrieve a csipsimple string config value
     * 
     * @param ctxt The context of your app
     * @param key the key for the setting you want to get
     * @param defaultValue the value you want to return if nothing found
     * @return the preference value
     */
public static String getPreferenceStringValue(Context ctxt, String key, String defaultValue) {
    String value = defaultValue;
    Uri uri = getPrefUriForKey(key);
    Cursor c = ctxt.getContentResolver().query(uri, null, String.class.getName(), null, null);
    if (c != null) {
        c.moveToFirst();
        String strValue = c.getString(1);
        if (strValue != null) {
            value = strValue;
        }
        c.close();
    }
    return value;
}

83. SipConfigManager#getPreferenceBooleanValue()

Project: CSipSimple
Source File: SipConfigManager.java
View license
/**
     * Helper method to retrieve a csipsimple boolean config value
     * 
     * @param ctxt The context of your app
     * @param key the key for the setting you want to get
     * @param defaultValue the value you want to return if nothing found
     * @return the preference value
     */
public static Boolean getPreferenceBooleanValue(Context ctxt, String key, Boolean defaultValue) {
    Boolean value = defaultValue;
    Uri uri = getPrefUriForKey(key);
    Cursor c = ctxt.getContentResolver().query(uri, null, Boolean.class.getName(), null, null);
    if (c != null) {
        c.moveToFirst();
        int intValue = c.getInt(1);
        if (intValue >= 0) {
            value = (intValue == 1);
        }
        c.close();
    }
    return value;
}

84. SipConfigManager#getPreferenceFloatValue()

Project: CSipSimple
Source File: SipConfigManager.java
View license
/**
     * Helper method to retrieve a csipsimple float config value
     * 
     * @param ctxt The context of your app
     * @param key the key for the setting you want to get
     * @param defaultValue the value you want to return if nothing found
     * @return the preference value
     */
public static Float getPreferenceFloatValue(Context ctxt, String key, Float defaultValue) {
    Float value = defaultValue;
    Uri uri = getPrefUriForKey(key);
    Cursor c = ctxt.getContentResolver().query(uri, null, Float.class.getName(), null, null);
    if (c != null) {
        c.moveToFirst();
        Float fValue = c.getFloat(1);
        if (fValue != null) {
            value = fValue;
        }
        c.close();
    }
    return value;
}

85. NotificationUtils#showNotification()

View license
public static void showNotification(Context context, Class<? extends Activity> activityClass, String title, String message, @DrawableRes int icon, int notificationId) {
    Intent intent = new Intent(context, activityClass);
    intent.putExtra(GcmConsts.EXTRA_GCM_MESSAGE, message);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context).setSmallIcon(icon).setContentTitle(title).setContentText(message).setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationId, notificationBuilder.build());
}

86. ContentFilesystem#removeFileAtLocalURL()

Project: reacteu-app
Source File: ContentFilesystem.java
View license
@Override
public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws NoModificationAllowedException {
    Uri contentUri = toNativeUri(inputURL);
    try {
        context.getContentResolver().delete(contentUri, null, null);
    } catch (UnsupportedOperationException t) {
        throw new NoModificationAllowedException("Deleting not supported for content uri: " + contentUri);
    }
    return true;
}

87. ContentFilesystem#toLocalUri()

Project: reacteu-app
Source File: ContentFilesystem.java
View license
@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
    if (!"content".equals(inputURL.getScheme())) {
        return null;
    }
    String subPath = inputURL.getEncodedPath();
    if (subPath.length() > 0) {
        subPath = subPath.substring(1);
    }
    Uri.Builder b = new Uri.Builder().scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL).authority("localhost").path(name).appendPath(inputURL.getAuthority());
    if (subPath.length() > 0) {
        b.appendEncodedPath(subPath);
    }
    Uri localUri = b.encodedQuery(inputURL.getEncodedQuery()).encodedFragment(inputURL.getEncodedFragment()).build();
    return LocalFilesystemURL.parse(localUri);
}

88. IconUtils#getIconUri()

View license
private static Uri getIconUri(Context context, String iconSource) {
    Uri ret = null;
    if (iconSource != null) {
        try {
            ret = Uri.parse(iconSource);
            // Verify scheme is set, so that relative uri (used by static resources) are not handled.
            if (ret.getScheme() == null) {
                ret = null;
            }
        } catch (Exception e) {
        }
        if (ret == null) {
            ret = sResDrawableIdHelper.getResourceDrawableUri(context, iconSource);
        }
    }
    return ret;
}

89. FrescoBasedReactTextInlineImageShadowNode#setSource()

View license
@ReactProp(name = "src")
public void setSource(@Nullable ReadableArray sources) {
    final String source = (sources == null || sources.size() == 0) ? null : sources.getMap(0).getString("uri");
    Uri uri = null;
    if (source != null) {
        try {
            uri = Uri.parse(source);
            // Verify scheme is set, so that relative uri (used by static resources) are not handled.
            if (uri.getScheme() == null) {
                uri = null;
            }
        } catch (Exception e) {
        }
        if (uri == null) {
            uri = getResourceDrawableUri(getThemedContext(), source);
        }
    }
    if (uri != mUri) {
        markUpdated();
    }
    mUri = uri;
}

90. MyFirebaseMessagingService#sendNotification()

View license
// [END receive_message]
/**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, /* Request code */
    intent, PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_stat_ic_notification).setContentTitle("FCM Message").setContentText(messageBody).setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, /* ID of notification */
    notificationBuilder.build());
}

91. Id3Reader#getFile()

Project: QuickLyric
Source File: Id3Reader.java
View license
public static File getFile(Context context, String artist, String title) {
    if (!PermissionsChecker.requestPermission((Activity) context, "android.permission.READ_EXTERNAL_STORAGE", R.string.id3_read_rationale, Id3Reader.REQUEST_CODE))
        return null;
    Uri uri = Uri.parse("content://media/external/audio/media");
    String[] columns = new String[] { "artist", "title", "_data" };
    String[] args = new String[] { artist, title };
    Cursor cursor = context.getContentResolver().query(uri, columns, "artist=? AND title=?", args, null);
    if (cursor == null || cursor.getCount() == 0) {
        if (cursor != null)
            cursor.close();
        return null;
    }
    // TODO handle more than one file
    cursor.moveToFirst();
    String path = cursor.getString(2);
    cursor.close();
    return path == null ? null : new File(path);
}

92. RingtonePlayer#getNotification()

View license
private Uri getNotification() {
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    if (notification == null) {
        // notification is null, using backup
        notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        // but just incase
        if (notification == null) {
            // notification backup is null, using 2nd backup
            notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        }
    }
    return notification;
}

93. ContactHelper#getId()

Project: qksms
Source File: ContactHelper.java
View license
public static long getId(Context context, String address) {
    if (address == null || address.isEmpty() || validateEmail(address))
        return 0;
    Cursor cursor;
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
    ContentResolver contentResolver = context.getContentResolver();
    long id = 0;
    try {
        cursor = contentResolver.query(uri, new String[] { BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
        if (cursor.moveToNext())
            id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
        cursor.close();
    } catch (Exception e) {
        Log.d(TAG, "Failed to find ID for address " + address);
        e.printStackTrace();
    }
    return id;
}

94. PduCache#put()

Project: qksms
Source File: PduCache.java
View license
@Override
public synchronized boolean put(Uri uri, PduCacheEntry entry) {
    int msgBoxId = entry.getMessageBox();
    HashSet<Uri> msgBox = mMessageBoxes.get(msgBoxId);
    if (msgBox == null) {
        msgBox = new HashSet<Uri>();
        mMessageBoxes.put(msgBoxId, msgBox);
    }
    long threadId = entry.getThreadId();
    HashSet<Uri> thread = mThreads.get(threadId);
    if (thread == null) {
        thread = new HashSet<Uri>();
        mThreads.put(threadId, thread);
    }
    Uri finalKey = normalizeKey(uri);
    boolean result = super.put(finalKey, entry);
    if (result) {
        msgBox.add(finalKey);
        thread.add(finalKey);
    }
    setUpdating(uri, false);
    return result;
}

95. PduCache#normalizeKey()

Project: qksms
Source File: PduCache.java
View license
/**
     * @param uri The Uri to be normalized.
     * @return Uri The normalized key of cached entry.
     */
private Uri normalizeKey(Uri uri) {
    int match = URI_MATCHER.match(uri);
    Uri normalizedKey = null;
    switch(match) {
        case MMS_ALL_ID:
            normalizedKey = uri;
            break;
        case MMS_INBOX_ID:
        case MMS_SENT_ID:
        case MMS_DRAFTS_ID:
        case MMS_OUTBOX_ID:
            String msgId = uri.getLastPathSegment();
            normalizedKey = Uri.withAppendedPath(Uri.parse("content://mms"), msgId);
            break;
        default:
            return null;
    }
    if (LOCAL_LOGV)
        Log.v(TAG, uri + " -> " + normalizedKey);
    return normalizedKey;
}

96. ContactHelper#getName()

Project: qksms
Source File: ContactHelper.java
View license
public static String getName(Context context, String address) {
    if (address == null || address.isEmpty() || validateEmail(address))
        return address;
    Cursor cursor;
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
    ContentResolver contentResolver = context.getContentResolver();
    String name = address;
    try {
        cursor = contentResolver.query(uri, new String[] { BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
        if (cursor.moveToNext())
            name = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
        cursor.close();
    } catch (Exception e) {
        Log.d(TAG, "Failed to find name for address " + address);
        e.printStackTrace();
    }
    return name;
}

97. RecipientIdCache#updateCanonicalAddressInDb()

Project: qksms
Source File: RecipientIdCache.java
View license
private void updateCanonicalAddressInDb(long id, String number) {
    if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
        Log.d(TAG, "[RecipientIdCache] updateCanonicalAddressInDb: id=" + id + ", number=" + number);
    }
    final ContentValues values = new ContentValues();
    values.put(Telephony.CanonicalAddressesColumns.ADDRESS, number);
    final StringBuilder buf = new StringBuilder(Telephony.CanonicalAddressesColumns._ID);
    buf.append('=').append(id);
    final Uri uri = ContentUris.withAppendedId(sSingleCanonicalAddressUri, id);
    final ContentResolver cr = mContext.getContentResolver();
    // We're running on the UI thread so just fire & forget, hope for the best.
    // (We were ignoring the return value anyway...)
    new Thread("updateCanonicalAddressInDb") {

        public void run() {
            cr.update(uri, values, buf.toString(), null);
        }
    }.start();
}

98. DeleteUnreadMessageService#onHandleIntent()

View license
@Override
protected void onHandleIntent(Intent intent) {
    Uri threadUri = intent.getParcelableExtra(EXTRA_THREAD_URI);
    // The messages are marked as read before deleting due to an issue with the android content
    // provider. When the message is deleted, it doesn't notify the conversations table. So if
    // there is an unread message, and it's deleted, then the conversation will remain unread.
    // Then even when you try to mark it as read and it iterates over unread messages to mark
    // them read, it won't be able to find any because they were deleted, leaving the
    // conversation "stuck" as unread. The only way to un-stick it is to receive a new message
    // in the conversation and mark that as read. Marking them read before deleting them solves
    // this problem.
    ArrayList<Message> messages = SmsHelper.getUnreadMessagesLegacy(this, threadUri);
    for (Message message : messages) {
        message.markRead();
        message.delete();
    }
    NotificationManager.update(this);
}

99. DataLayer#getGitHubRepositorySearch()

Project: reark
Source File: DataLayer.java
View license
@NonNull
public Observable<DataStreamNotification<GitHubRepositorySearch>> getGitHubRepositorySearch(@NonNull final String searchString) {
    Preconditions.checkNotNull(searchString, "Search string Store cannot be null.");
    final Uri uri = gitHubRepositorySearchStore.getUriForId(searchString);
    final Observable<NetworkRequestStatus> networkRequestStatusObservable = networkRequestStatusStore.getStream(uri.toString().hashCode());
    final Observable<GitHubRepositorySearch> gitHubRepositorySearchObservable = gitHubRepositorySearchStore.getStream(searchString);
    return DataLayerUtils.createDataStreamNotificationObservable(networkRequestStatusObservable, gitHubRepositorySearchObservable);
}

100. Conversation#startQueryHaveLockedMessages()

Project: qksms
Source File: Conversation.java
View license
/**
     * Check for locked messages in all threads or a specified thread.
     *
     * @param handler   An AsyncQueryHandler that will receive onQueryComplete
     *                  upon completion of looking for locked messages
     * @param threadIds A list of threads to search. null means all threads
     * @param token     The token that will be passed to onQueryComplete
     */
public static void startQueryHaveLockedMessages(AsyncQueryHandler handler, Collection<Long> threadIds, int token) {
    handler.cancelOperation(token);
    Uri uri = MmsSms.CONTENT_LOCKED_URI;
    String selection = null;
    if (threadIds != null) {
        StringBuilder buf = new StringBuilder();
        int i = 0;
        for (long threadId : threadIds) {
            if (i++ > 0) {
                buf.append(" OR ");
            }
            // We have to build the selection arg into the selection because deep down in
            // provider, the function buildUnionSubQuery takes selectionArgs, but ignores it.
            buf.append(Mms.THREAD_ID).append("=").append(Long.toString(threadId));
        }
        selection = buf.toString();
    }
    handler.startQuery(token, threadIds, uri, ALL_THREADS_PROJECTION, selection, null, Conversations.DEFAULT_SORT_ORDER);
}