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. 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() {
            }
        });
}

18. 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();
}

19. 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)));
    }
}

20. 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;
    }
}

21. 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);
}

22. 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;
}

23. 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();
}

24. 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();
}

25. 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();
}

26. 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;
}

27. 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();
}

28. 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);
}

29. 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);
}

30. 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);
}

31. 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);
}

32. 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);
}

33. 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;
    }
}

34. 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);
}

35. 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();
    }
}

36. RouterActivity#onCreate()

Project: ActivityRouter
Source File: RouterActivity.java
View license
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RouterCallback callback = getRouterCallback();
    Uri uri = getIntent().getData();
    if (uri != null) {
        if (callback == null) {
            Routers.open(this, uri);
        } else {
            callback.beforeOpen(this, uri);
            boolean success = Routers.open(this, uri);
            if (success) {
                callback.afterOpen(this, uri);
            } else {
                callback.notFound(this, uri);
            }
        }
    }
    finish();
}

37. ForecastFragment#onCreateLoader()

View license
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    // This is called when a new Loader needs to be created.  This
    // fragment only uses one loader, so we don't care about checking the id.
    // To only show current and future dates, filter the query to return weather only for
    // dates after or including today.
    // Sort order:  Ascending, by date.
    String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
    String locationSetting = Utility.getPreferredLocation(getActivity());
    Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis());
    return new CursorLoader(getActivity(), weatherForLocationUri, FORECAST_COLUMNS, null, null, sortOrder);
}

38. WeatherMuzeiSource#onUpdate()

View license
@Override
protected void onUpdate(int reason) {
    String location = Utility.getPreferredLocation(this);
    Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(location, System.currentTimeMillis());
    Cursor cursor = getContentResolver().query(weatherForLocationUri, FORECAST_COLUMNS, null, null, WeatherContract.WeatherEntry.COLUMN_DATE + " ASC");
    if (cursor.moveToFirst()) {
        int weatherId = cursor.getInt(INDEX_WEATHER_ID);
        String desc = cursor.getString(INDEX_SHORT_DESC);
        String imageUrl = Utility.getImageUrlForWeatherCondition(weatherId);
        // Only publish a new wallpaper if we have a valid image
        if (imageUrl != null) {
            publishArtwork(new Artwork.Builder().imageUri(Uri.parse(imageUrl)).title(desc).byline(location).viewIntent(new Intent(this, MainActivity.class)).build());
        }
    }
    cursor.close();
}

39. MediaStoreHack#delete()

View license
/**
     * Deletes the file. Returns true if the file has been successfully deleted or otherwise does
     * not exist. This operation is not recursive.
     */
public static boolean delete(final Context context, final File file) {
    final String where = MediaStore.MediaColumns.DATA + "=?";
    final String[] selectionArgs = new String[] { file.getAbsolutePath() };
    final ContentResolver contentResolver = context.getContentResolver();
    final Uri filesUri = MediaStore.Files.getContentUri("external");
    // Delete the entry from the media database. This will actually delete media files.
    contentResolver.delete(filesUri, where, selectionArgs);
    // If the file is not a media file, create a new entry.
    if (file.exists()) {
        final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
        contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        // Delete the created entry, such that content provider will delete the file.
        contentResolver.delete(filesUri, where, selectionArgs);
    }
    return !file.exists();
}

40. MediaStoreHack#mkdir()

View license
public static boolean mkdir(final Context context, final File file) throws IOException {
    if (file.exists()) {
        return file.isDirectory();
    }
    final File tmpFile = new File(file, ".MediaWriteTemp");
    final int albumId = getTemporaryAlbumId(context);
    if (albumId == 0) {
        throw new IOException("Failed to create temporary album id.");
    }
    final Uri albumUri = Uri.parse(String.format(Locale.US, ALBUM_ART_URI + "/%d", albumId));
    final ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, tmpFile.getAbsolutePath());
    final ContentResolver contentResolver = context.getContentResolver();
    if (contentResolver.update(albumUri, values, null, null) == 0) {
        values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId);
        contentResolver.insert(Uri.parse(ALBUM_ART_URI), values);
    }
    try {
        final ParcelFileDescriptor fd = contentResolver.openFileDescriptor(albumUri, "r");
        fd.close();
    } finally {
        delete(context, tmpFile);
    }
    return file.exists();
}

41. Futils#fileToContentUri()

Project: AmazeFileManager
Source File: Futils.java
View license
public static Uri fileToContentUri(Context context, File file) {
    // Normalize the path to ensure media search
    final String normalizedPath = normalizeMediaPath(file.getAbsolutePath());
    // Check in external and internal storages
    Uri uri = fileToContentUri(context, normalizedPath, EXTERNAL_VOLUME);
    if (uri != null) {
        return uri;
    }
    uri = fileToContentUri(context, normalizedPath, INTERNAL_VOLUME);
    if (uri != null) {
        return uri;
    }
    return null;
}

42. FileDataStorageManager#removeFolderInDb()

Project: android
Source File: FileDataStorageManager.java
View license
private boolean removeFolderInDb(OCFile folder) {
    Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, "" + // URI for recursive deletion
    folder.getFileId());
    String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
    String[] whereArgs = new String[] { mAccount.name, folder.getRemotePath() };
    int deleted = 0;
    if (getContentProviderClient() != null) {
        try {
            deleted = getContentProviderClient().delete(folder_uri, where, whereArgs);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    } else {
        deleted = getContentResolver().delete(folder_uri, where, whereArgs);
    }
    return deleted > 0;
}

43. FileDataStorageManager#removeShare()

Project: android
Source File: FileDataStorageManager.java
View license
public void removeShare(OCShare share) {
    Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
    String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta._ID + "=?";
    String[] whereArgs = new String[] { mAccount.name, Long.toString(share.getId()) };
    if (getContentProviderClient() != null) {
        try {
            getContentProviderClient().delete(share_uri, where, whereArgs);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    } else {
        getContentResolver().delete(share_uri, where, whereArgs);
    }
}

44. FileContentProvider#insert()

Project: android
Source File: FileContentProvider.java
View license
@Override
public Uri insert(Uri uri, ContentValues values) {
    Uri newUri = null;
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        newUri = insert(db, uri, values);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    getContext().getContentResolver().notifyChange(newUri, null);
    return newUri;
}

45. AssetFileLibraryLicenseDataCollector#loadLicenseInfo()

View license
private LibraryInfo loadLicenseInfo(AssetManager assets, String dirname) {
    String name = loadTextFile(assets, dirname + "/NAME");
    String license = loadTextFile(assets, dirname + "/LICENSE");
    String notice = loadTextFile(assets, dirname + "/NOTICE");
    Uri link = safeParseLinkUri(loadTextFile(assets, dirname + "/LINK"));
    if (name != null && (license != null || notice != null)) {
        LibraryInfo info = new LibraryInfo();
        info.mLibraryName = name;
        info.mLicenseText = license;
        info.mNoticeText = notice;
        info.mLink = link;
        return info;
    } else {
        Log.w(TAG, "Failed to load " + dirname);
        return null;
    }
}

46. AlarmPreferenceListAdapter#setMathAlarm()

View license
public void setMathAlarm(Alarm alarm) {
    this.alarm = alarm;
    preferences.clear();
    preferences.add(new AlarmPreference(AlarmPreference.Key.ALARM_ACTIVE, "Active", null, null, alarm.getAlarmActive(), Type.BOOLEAN));
    preferences.add(new AlarmPreference(AlarmPreference.Key.ALARM_NAME, "Label", alarm.getAlarmName(), null, alarm.getAlarmName(), Type.STRING));
    preferences.add(new AlarmPreference(AlarmPreference.Key.ALARM_TIME, "Set time", alarm.getAlarmTimeString(), null, alarm.getAlarmTime(), Type.TIME));
    preferences.add(new AlarmPreference(AlarmPreference.Key.ALARM_REPEAT, "Repeat", alarm.getRepeatDaysString(), repeatDays, alarm.getDays(), Type.MULTIPLE_LIST));
    preferences.add(new AlarmPreference(AlarmPreference.Key.ALARM_DIFFICULTY, "Difficulty", alarm.getDifficulty().toString(), alarmDifficulties, alarm.getDifficulty(), Type.LIST));
    Uri alarmToneUri = Uri.parse(alarm.getAlarmTonePath());
    Ringtone alarmTone = RingtoneManager.getRingtone(getContext(), alarmToneUri);
    if (alarmTone instanceof Ringtone && !alarm.getAlarmTonePath().equalsIgnoreCase("")) {
        preferences.add(new AlarmPreference(AlarmPreference.Key.ALARM_TONE, "Ringtone", alarmTone.getTitle(getContext()), alarmTones, alarm.getAlarmTonePath(), Type.LIST));
    } else {
        preferences.add(new AlarmPreference(AlarmPreference.Key.ALARM_TONE, "Ringtone", getAlarmTones()[0], alarmTones, null, Type.LIST));
    }
    preferences.add(new AlarmPreference(AlarmPreference.Key.ALARM_VIBRATE, "Vibrate", null, null, alarm.getVibrate(), Type.BOOLEAN));
}

47. SampleActivity#insertPerson()

View license
/**
     * Insert a person.
     *
     * @return the id of the created person.
     */
private long insertPerson(long mainTeamId, long secondaryTeamId, @NonNull String firstName, @NonNull String lastName, int age, Date birthDate, boolean hasBlueEyes, Float height, @NonNull Gender gender, @NonNull String countryCode) {
    PersonContentValues values = new PersonContentValues();
    values.putFirstName(firstName);
    values.putLastName(lastName);
    values.putAge(age);
    values.putBirthDate(birthDate);
    values.putHasBlueEyes(hasBlueEyes);
    values.putHeight(height);
    values.putGender(gender);
    values.putCountryCode(countryCode);
    Uri uri = values.insert(getContentResolver());
    return ContentUris.parseId(uri);
}

48. BaseImage#fullSizeBitmap()

Project: android-cropimage
Source File: BaseImage.java
View license
public Bitmap fullSizeBitmap(int minSideLength, int maxNumberOfPixels, boolean rotateAsNeeded, boolean useNative) {
    Uri url = mContainer.contentUri(mId);
    if (url == null)
        return null;
    Bitmap b = Util.makeBitmap(minSideLength, maxNumberOfPixels, url, mContentResolver, useNative);
    if (b != null && rotateAsNeeded) {
        b = Util.rotate(b, getDegreesRotated());
    }
    return b;
}

49. ImageList#getBucketIds()

Project: android-cropimage
Source File: ImageList.java
View license
public HashMap<String, String> getBucketIds() {
    Uri uri = mBaseUri.buildUpon().appendQueryParameter("distinct", "true").build();
    Cursor cursor = Media.query(mContentResolver, uri, new String[] { Media.BUCKET_DISPLAY_NAME, Media.BUCKET_ID }, whereClause(), whereClauseArgs(), null);
    try {
        HashMap<String, String> hash = new HashMap<String, String>();
        while (cursor.moveToNext()) {
            hash.put(cursor.getString(1), cursor.getString(0));
        }
        return hash;
    } finally {
        cursor.close();
    }
}

50. VideoList#getBucketIds()

Project: android-cropimage
Source File: VideoList.java
View license
public HashMap<String, String> getBucketIds() {
    Uri uri = mBaseUri.buildUpon().appendQueryParameter("distinct", "true").build();
    Cursor c = Images.Media.query(mContentResolver, uri, new String[] { Media.BUCKET_DISPLAY_NAME, Media.BUCKET_ID }, whereClause(), whereClauseArgs(), sortOrder());
    try {
        HashMap<String, String> hash = new HashMap<String, String>();
        while (c.moveToNext()) {
            hash.put(c.getString(1), c.getString(0));
        }
        return hash;
    } finally {
        c.close();
    }
}

51. MainActivity#onActivityResult()

View license
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(MainActivity.class.getSimpleName(), "requestCode:" + requestCode + " resultCode:" + resultCode);
    if (mUploadMessage == null)
        return;
    Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
    if (result == null)
        return;
    mUploadMessage.onReceiveValue(result);
    mUploadMessage = null;
    Bitmap bm = null;
    ContentResolver resolver = getContentResolver();
    try {
        bm = MediaStore.Images.Media.getBitmap(resolver, result);
        mImageView.setImageBitmap(bm);
        bm = null;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

52. CropImage#getCameraIntents()

View license
/**
     * Get all Camera intents for capturing image using device camera apps.
     */
public static List<Intent> getCameraIntents(@NonNull Context context, @NonNull PackageManager packageManager) {
    List<Intent> allIntents = new ArrayList<>();
    // Determine Uri of camera image to  save.
    Uri outputFileUri = getCaptureImageOutputUri(context);
    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam) {
        Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(res.activityInfo.packageName);
        if (outputFileUri != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        }
        allIntents.add(intent);
    }
    return allIntents;
}

53. CropImageActivity#onCreate()

View license
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.crop_image_activity);
    mCropImageView = (CropImageView) findViewById(R.id.cropImageView);
    Intent intent = getIntent();
    Uri source = intent.getParcelableExtra(CropImage.CROP_IMAGE_EXTRA_SOURCE);
    mOptions = intent.getParcelableExtra(CropImage.CROP_IMAGE_EXTRA_OPTIONS);
    if (savedInstanceState == null) {
        mCropImageView.setImageUriAsync(source);
    }
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        String title = mOptions.activityTitle != null && !mOptions.activityTitle.isEmpty() ? mOptions.activityTitle : getResources().getString(R.string.crop_image_activity_title);
        actionBar.setTitle(title);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

54. ContentBrowserActivity#onCreateOptionsMenu()

View license
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.content_actions, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(this);
    // Set file with share history to the provider and set the share intent.
    MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);
    ShareActionProvider actionProvider = (ShareActionProvider) actionItem.getActionProvider();
    actionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
    // Note that you can set/change the intent any time,
    // say when the user has selected an image.
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/*");
    Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    actionProvider.setShareIntent(shareIntent);
    return true;
}

55. OverscanActivity#onCreateOptionsMenu()

View license
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.content_actions, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(this);
    // Set file with share history to the provider and set the share intent.
    MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);
    ShareActionProvider actionProvider = (ShareActionProvider) actionItem.getActionProvider();
    actionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
    // Note that you can set/change the intent any time,
    // say when the user has selected an image.
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/*");
    Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    actionProvider.setShareIntent(shareIntent);
    return true;
}

56. VideoPlayerActivity#onCreateOptionsMenu()

View license
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.content_actions, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(this);
    // Set file with share history to the provider and set the share intent.
    MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);
    ShareActionProvider actionProvider = (ShareActionProvider) actionItem.getActionProvider();
    actionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
    // Note that you can set/change the intent any time,
    // say when the user has selected an image.
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/*");
    Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    actionProvider.setShareIntent(shareIntent);
    return true;
}

57. BleProfileService#onStartCommand()

View license
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS))
        throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key");
    final Uri logUri = intent.getParcelableExtra(EXTRA_LOG_URI);
    mLogSession = Logger.openSession(getApplicationContext(), logUri);
    mDeviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
    Logger.i(mLogSession, "Service started");
    // notify user about changing the state to CONNECTING
    final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE);
    broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING);
    LocalBroadcastManager.getInstance(BleProfileService.this).sendBroadcast(broadcast);
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    final BluetoothAdapter adapter = bluetoothManager.getAdapter();
    final BluetoothDevice device = adapter.getRemoteDevice(mDeviceAddress);
    mDeviceName = device.getName();
    onServiceStarted();
    mBleManager.connect(device);
    return START_REDELIVER_INTENT;
}

58. BaseImageDownloader#getStreamFromContent()

View license
/**
	 * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}).
	 *
	 * @param imageUri Image URI
	 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
	 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
	 * @return {@link InputStream} of image
	 * @throws 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 (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());
        }
    }
    return res.openInputStream(uri);
}

59. GlobalAppController#playerSetDataSource()

View license
private void playerSetDataSource(int index) {
    IBasicMediaPlayer player = getPlayer(index);
    Uri uri = getPlayerStateStore().getMediaUri(index);
    if (player != null && uri != null) {
        try {
            MediaMetadata metadata;
            metadata = MediaMetadataBuilder.create(mContext, uri);
            player.setDataSource(mContext, uri);
            mMetadata[index] = metadata;
            setPlayerState(index, PLAYER_STATE_INITIALIZED);
        } catch (final Exception e) {
            notifyPlayerExceptionOccurred(index, "setDataSource", e);
        }
    }
}

60. OrmLiteDefaultContentProvider#insert()

View license
/*
     * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
     */
@Override
public Uri insert(Uri uri, ContentValues values) {
    Uri result = null;
    if (!controller.hasPreinitialized()) {
        throw new IllegalStateException("Controller has not been initialized.");
    }
    int patternCode = controller.getUriMatcher().match(uri);
    MatcherPattern pattern = controller.findMatcherPattern(patternCode);
    if (pattern == null) {
        throw new IllegalArgumentException("unknown uri : " + uri.toString());
    }
    Parameter parameter = new Parameter(uri, values);
    SQLiteDatabase db = this.getHelper().getWritableDatabase();
    result = onInsert(this.getHelper(), db, pattern, parameter);
    if (result != null) {
        this.onInsertCompleted(result, uri, pattern, parameter);
    }
    return result;
}

61. OrmLiteSimpleContentProvider#onInsert()

View license
/*
     * @see
     * com.tojc.ormlite.android.OrmLiteDefaultContentProvider#onInsert(com.j256
     * .ormlite.android. apptools.OrmLiteSqliteOpenHelper,
     * com.tojc.ormlite.android.framework.MatcherPattern,
     * com.tojc.ormlite.android.framework.OperationParameters.InsertParameters)
     */
@Override
public Uri onInsert(T helper, SQLiteDatabase db, MatcherPattern target, InsertParameters parameter) {
    Uri result = null;
    long id = db.insert(target.getTableInfo().getName(), null, parameter.getValues());
    if (id >= 0) {
        result = ContentUris.withAppendedId(target.getContentUriPattern(), id);
    } else {
        throw new SQLException("Failed to insert row into : " + parameter.getUri().toString());
    }
    return result;
}

62. Utils#startMarketActivity()

Project: android-proxy
Source File: Utils.java
View license
public static void startMarketActivity(Context ctx) {
    Uri marketUri = getMarketUri(App.getInstance().activeMarket);
    boolean marketShown = false;
    try {
        ctx.startActivity(new Intent(Intent.ACTION_VIEW, marketUri));
        marketShown = true;
    } catch (Exception e) {
        Timber.e(e, "Exception starting Market activity: '%s", marketUri.toString());
    }
    if (!marketShown) {
        Toast.makeText(ctx, R.string.market_not_found, Toast.LENGTH_SHORT).show();
    }
}

63. MediaProcessor#processContentProviderMedia()

View license
private InputStream processContentProviderMedia(String sourceFile) {
    ContentResolver resolver = RTApi.getApplicationContext().getContentResolver();
    Uri uri = Uri.parse(sourceFile);
    InputStream in = null;
    try {
        in = resolver.openInputStream(uri);
    } catch (IOException ioe) {
        Log.e(getClass().getSimpleName(), ioe.getMessage(), ioe);
    }
    return in;
}

64. MainActivity#getRandomImageUri()

View license
// Get the uri to a random image in the photo gallery
private Uri getRandomImageUri() {
    Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String[] projection = { MediaStore.Images.Media._ID };
    Cursor cursor = null;
    try {
        cursor = getContentResolver().query(mediaUri, projection, null, null, null);
        cursor.moveToPosition((int) (Math.random() * cursor.getCount()));
        String id = cursor.getString(0);
        Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
        return uri;
    } catch (Exception e) {
        return null;
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }
}

65. BaseImageDownloader#getStreamFromContent()

View license
/**
	 * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}).
	 *
	 * @param imageUri Image URI
	 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
	 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
	 * @return {@link InputStream} of image
	 * @throws 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
    isVideoContentUri(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 getContactPhotoStream(uri);
    }
    return res.openInputStream(uri);
}

66. ImageUtils#scaleDownBitmapForUri()

Project: android-utils
Source File: ImageUtils.java
View license
/**
	 * Scales the image independently of the screen density of the device. Maintains image aspect
	 * ratio.
	 * 
	 * @param uri
	 *            Uri of the source bitmap
	 **/
public static Uri scaleDownBitmapForUri(Context ctx, Uri uri, int newHeight) throws FileNotFoundException, IOException {
    if (uri == null)
        throw new NullPointerException(ERROR_URI_NULL);
    if (!MediaUtils.isMediaContentUri(uri))
        return null;
    Bitmap original = Media.getBitmap(ctx.getContentResolver(), uri);
    Bitmap bmp = scaleBitmap(ctx, original, newHeight);
    Uri destUri = null;
    String uriStr = Utils.writeImageToMedia(ctx, bmp, "", "");
    if (uriStr != null) {
        destUri = Uri.parse(uriStr);
    }
    return destUri;
}

67. Utils#createImageUri()

Project: android-utils
Source File: Utils.java
View license
@Nullable
public static /**
     * Creates external content:// scheme uri to save the images at. The image saved at this
     * {@link android.net.Uri} will be visible via the gallery application on the device.
     **/
Uri createImageUri(Context ctx) throws IOException {
    if (ctx == null) {
        throw new NullPointerException("Context cannot be null");
    }
    Uri imageUri = null;
    ContentValues values = new ContentValues();
    values.put(MediaColumns.TITLE, "");
    values.put(ImageColumns.DESCRIPTION, "");
    imageUri = ctx.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
    return imageUri;
}

68. Utils#createVideoUri()

Project: android-utils
Source File: Utils.java
View license
@Nullable
public static /**
     * Creates external content:// scheme uri to save the videos at.
     **/
Uri createVideoUri(Context ctx) throws IOException {
    if (ctx == null) {
        throw new NullPointerException("Context cannot be null");
    }
    Uri imageUri = null;
    ContentValues values = new ContentValues();
    values.put(MediaColumns.TITLE, "");
    values.put(ImageColumns.DESCRIPTION, "");
    imageUri = ctx.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI, values);
    return imageUri;
}

69. YouTubeUtils#isYouTubeUrl()

Project: android-utils
Source File: YouTubeUtils.java
View license
/****
     * Checks to see if the your contains the authority "youtube.com"
     ****/
public static boolean isYouTubeUrl(String url) {
    if (TextUtils.isEmpty(url)) {
        return false;
    }
    Uri uri = Uri.parse(url);
    String authority = uri.getAuthority();
    if (!TextUtils.isEmpty(authority) && authority.contains("youtube.com")) {
        return true;
    } else {
        return false;
    }
}

70. CommonUtil#openWebSite()

Project: Android-ZBLibrary
Source File: CommonUtil.java
View license
/**????
	 * @param context
	 * @param webSite
	 */
public static void openWebSite(Activity context, String webSite) {
    if (context == null || StringUtil.isNotEmpty(webSite, true) == false) {
        Log.e(TAG, "openWebSite  context == null || StringUtil.isNotEmpty(webSite, true) == false >> return;");
        return;
    }
    if (!webSite.startsWith("http://") && !webSite.startsWith("https://")) {
        webSite = "http://" + webSite;
    }
    final Uri uri = Uri.parse(webSite);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    toActivity(context, intent, -1);
}

71. CommonUtil#openWebSite()

Project: Android-ZBLibrary
Source File: CommonUtil.java
View license
/**????
	 * @param context
	 * @param webSite
	 */
public static void openWebSite(Activity context, String webSite) {
    if (context == null || StringUtil.isNotEmpty(webSite, true) == false) {
        Log.e(TAG, "openWebSite  context == null || StringUtil.isNotEmpty(webSite, true) == false >> return;");
        return;
    }
    if (!webSite.startsWith("http://") && !webSite.startsWith("https://")) {
        webSite = "http://" + webSite;
    }
    final Uri uri = Uri.parse(webSite);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    toActivity(context, intent, -1);
}

72. MessagesProviderTest#testInsertMessages()

View license
@Test
public void testInsertMessages() {
    String msgId = MessageUtils.messageId();
    Uri msg = MessagesProviderUtils.newOutgoingMessage(getMockContext(), msgId, TEST_USERID, "Test message for you", true);
    assertNotNull(msg);
    assertQueryValues(msg, Messages.MESSAGE_ID, msgId, Messages.BODY_CONTENT, "Test message for you", Messages.BODY_MIME, "text/plain", Messages.DIRECTION, String.valueOf(Messages.DIRECTION_OUT));
}

73. MessagesProviderTest#testDeleteThread()

View license
@Test
public void testDeleteThread() {
    String msgId = MessageUtils.messageId();
    Uri msg = MessagesProviderUtils.newOutgoingMessage(getMockContext(), msgId, TEST_USERID, "Test message for you", true);
    assertNotNull(msg);
    long threadId = MessagesProviderUtils.getThreadByMessage(getMockContext(), msg);
    assertTrue(threadId > 0);
    MessagesProviderUtils.deleteThread(getMockContext(), threadId, false);
    assertQueryCount(msg, 0);
    assertQueryCount(ContentUris.withAppendedId(Threads.CONTENT_URI, threadId), 0);
}

74. Conversation#addUsers()

Project: androidclient
Source File: Conversation.java
View license
public void addUsers(String[] members) {
    if (!isGroupChat())
        throw new UnsupportedOperationException("Not a group chat conversation");
    // add members to the group
    MessagesProviderUtils.addGroupMembers(mContext, mGroupJid, members, true);
    // store add group member command to outbox
    boolean encrypted = Preferences.getEncryptionEnabled(mContext);
    String msgId = MessageCenterService.messageId();
    Uri cmdMsg = KontalkGroupCommands.addGroupMembers(mContext, getThreadId(), mGroupJid, members, msgId, encrypted);
    // TODO check for null
    // send add group member command now
    MessageCenterService.addGroupMembers(mContext, mGroupJid, mGroupSubject, getGroupPeers(), members, encrypted, ContentUris.parseId(cmdMsg), msgId);
}

75. Conversation#removeUsers()

Project: androidclient
Source File: Conversation.java
View license
public void removeUsers(String[] members) {
    if (!isGroupChat())
        throw new UnsupportedOperationException("Not a group chat conversation");
    // remove members to the group
    MessagesProviderUtils.removeGroupMembers(mContext, mGroupJid, members, true);
    // store remove group member command to outbox
    boolean encrypted = Preferences.getEncryptionEnabled(mContext);
    String msgId = MessageCenterService.messageId();
    Uri cmdMsg = KontalkGroupCommands.removeGroupMembers(mContext, getThreadId(), mGroupJid, members, msgId, encrypted);
    // TODO check for null
    // send add group member command now
    MessageCenterService.removeGroupMembers(mContext, mGroupJid, mGroupSubject, getGroupPeers(), members, encrypted, ContentUris.parseId(cmdMsg), msgId);
}

76. AudioComponent#isValidMedia()

Project: androidclient
Source File: AudioComponent.java
View license
/** FIXME not used yet */
public boolean isValidMedia(Context context) {
    Uri localUri = mContent.getLocalUri();
    if (localUri != null) {
        try {
            return (MediaStorage.getLength(context, localUri) == mLength);
        } catch (Exception e) {
            return false;
        }
    }
    return false;
}

77. ImageComponent#isValidMedia()

Project: androidclient
Source File: ImageComponent.java
View license
/** FIXME not used yet */
public boolean isValidMedia(Context context) {
    Uri localUri = mContent.getLocalUri();
    if (localUri != null) {
        try {
            return (MediaStorage.getLength(context, localUri) == mLength);
        } catch (Exception e) {
            return false;
        }
    }
    return false;
}

78. MessagesProviderUtils#insertEmptyThread()

View license
/** Inserts an empty thread (that is, with no messages). */
public static long insertEmptyThread(Context context, String peer, String draft) {
    ContentValues msgValues = new ContentValues(9);
    // must supply a message ID...
    msgValues.put(Messages.MESSAGE_ID, "draft" + (new Random().nextInt()));
    // use group id as the peer
    msgValues.put(Messages.PEER, peer);
    msgValues.put(Messages.BODY_CONTENT, new byte[0]);
    msgValues.put(Messages.BODY_LENGTH, 0);
    msgValues.put(Messages.BODY_MIME, TextComponent.MIME_TYPE);
    msgValues.put(Messages.DIRECTION, Messages.DIRECTION_OUT);
    msgValues.put(Messages.TIMESTAMP, System.currentTimeMillis());
    msgValues.put(Messages.ENCRYPTED, false);
    if (draft != null)
        msgValues.put(Threads.DRAFT, draft);
    Uri newThread = context.getContentResolver().insert(Messages.CONTENT_URI, msgValues);
    return newThread != null ? ContentUris.parseId(newThread) : Messages.NO_THREAD;
}

79. MessageCenterService#handleRetry()

View license
@CommandHandler(name = ACTION_RETRY)
private boolean handleRetry(Intent intent) {
    Uri msgUri = intent.getParcelableExtra(EXTRA_MESSAGE);
    boolean encrypted = Preferences.getEncryptionEnabled(this);
    ContentValues values = new ContentValues(2);
    values.put(Messages.STATUS, Messages.STATUS_SENDING);
    values.put(Messages.SECURITY_FLAGS, encrypted ? Coder.SECURITY_BASIC : Coder.SECURITY_CLEARTEXT);
    getContentResolver().update(msgUri, values, null, null);
    // already connected: resend pending messages
    if (isConnected())
        resendPendingMessages(false, false);
    return false;
}

80. Syncer#commit()

Project: androidclient
Source File: Syncer.java
View license
private void commit(ContentProviderClient usersProvider, SyncResult syncResult) {
    // commit users table
    Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true").appendQueryParameter(Users.COMMIT, "true").build();
    try {
        usersProvider.update(uri, null, null, null);
        Log.d(TAG, "users database committed");
        Contact.invalidate();
    } catch (Exception e) {
        Log.e(TAG, "error committing users database - aborting sync", e);
        syncResult.databaseError = true;
    }
}

81. ConversationsActivity#startGroupChat()

View license
private void startGroupChat(List<Uri> threads) {
    String selfJid = Authenticator.getSelfJID(this);
    String groupId = StringUtils.randomString(20);
    String groupJid = KontalkGroupCommands.createGroupJid(groupId, selfJid);
    // ensure no duplicates
    Set<String> usersList = new HashSet<>();
    for (Uri uri : threads) {
        String member = uri.getLastPathSegment();
        // exclude ourselves
        if (!member.equalsIgnoreCase(selfJid))
            usersList.add(member);
    }
    if (usersList.size() > 0) {
        askGroupSubject(usersList, groupJid);
    }
}

82. SystemUtils#lookupPhoneNumber()

Project: androidclient
Source File: SystemUtils.java
View license
public static Uri lookupPhoneNumber(Context context, String phoneNumber) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cur = context.getContentResolver().query(uri, new String[] { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.LOOKUP_KEY }, null, null, null);
    if (cur != null) {
        try {
            if (cur.moveToNext()) {
                long id = cur.getLong(0);
                String lookupKey = cur.getString(1);
                return ContactsContract.Contacts.getLookupUri(id, lookupKey);
            }
        } finally {
            cur.close();
        }
    }
    return null;
}

83. DecodingAsyncTask#getSeekableFileDescriptor()

View license
protected ParcelFileDescriptor getSeekableFileDescriptor(String path) throws IOException {
    ParcelFileDescriptor pfd;
    File pdfCopy = new File(path);
    if (pdfCopy.exists()) {
        pfd = ParcelFileDescriptor.open(pdfCopy, ParcelFileDescriptor.MODE_READ_ONLY);
        return pfd;
    }
    if (!path.contains("://")) {
        path = String.format("file://%s", path);
    }
    Uri uri = Uri.parse(path);
    pfd = context.getContentResolver().openFileDescriptor(uri, "r");
    if (pfd == null) {
        throw new IOException("Cannot get FileDescriptor for " + path);
    }
    return pfd;
}

84. ShortCutUtil#hasShortcut()

Project: AndroidStudyDemo
Source File: ShortCutUtil.java
View license
/**
     * ?????????
     *
     * @param activity Activity
     * @return ????????
     */
public static boolean hasShortcut(Activity activity) {
    boolean isInstallShortcut = false;
    final ContentResolver cr = activity.getContentResolver();
    final String AUTHORITY = "com.android.launcher.settings";
    final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");
    Cursor c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { activity.getString(R.string.app_name).trim() }, null);
    if (c != null && c.getCount() > 0) {
        isInstallShortcut = true;
    }
    return isInstallShortcut;
}

85. SystemIntentUtil#sendMessage()

View license
/**
     * ?????????
     *
     * @param activity    Activity
     * @param phoneNumber ????
     * @param smsContent  ????
     */
public static void sendMessage(Context activity, String phoneNumber, String smsContent) {
    if (phoneNumber == null || phoneNumber.length() < 4) {
        return;
    }
    Uri uri = Uri.parse("smsto:" + phoneNumber);
    Intent it = new Intent(Intent.ACTION_SENDTO, uri);
    it.putExtra("sms_body", smsContent);
    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(it);
}

86. VideoProvider#insert()

View license
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
    final Uri returnUri;
    final int match = sUriMatcher.match(uri);
    switch(match) {
        case VIDEO:
            {
                long _id = mOpenHelper.getWritableDatabase().insert(VideoContract.VideoEntry.TABLE_NAME, null, values);
                if (_id > 0) {
                    returnUri = VideoContract.VideoEntry.buildVideoUri(_id);
                } else {
                    throw new SQLException("Failed to insert row into " + uri);
                }
                break;
            }
        default:
            {
                throw new UnsupportedOperationException("Unknown uri: " + uri);
            }
    }
    mContentResolver.notifyChange(uri, null);
    return returnUri;
}

87. PlaybackOverlayFragment#getRendererBuilder()

View license
private VideoPlayer.RendererBuilder getRendererBuilder() {
    String userAgent = Util.getUserAgent(getContext(), "ExoVideoPlayer");
    Uri contentUri = Uri.parse(mSelectedVideo.videoUrl);
    int contentType = Util.inferContentType(contentUri.getLastPathSegment());
    switch(contentType) {
        case Util.TYPE_OTHER:
            {
                return new ExtractorRendererBuilder(getContext(), userAgent, contentUri);
            }
        default:
            {
                throw new IllegalStateException("Unsupported type: " + contentType);
            }
    }
}

88. RichFeedUtil#getRichTvListings()

View license
public static XmlTvParser.TvListing getRichTvListings(Context context) {
    Uri catalogUri = USE_LOCAL_XML_FEED ? Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.rich_tv_input_xmltv_feed) : Uri.parse(context.getResources().getString(R.string.rich_input_feed_url)).normalizeScheme();
    if (sSampleTvListing != null) {
        return sSampleTvListing;
    }
    try (InputStream inputStream = getInputStream(context, catalogUri)) {
        sSampleTvListing = XmlTvParser.parse(inputStream);
    } catch (IOException e) {
        Log.e(TAG, "Error in fetching " + catalogUri, e);
    }
    return sSampleTvListing;
}

89. TvContractUtils#buildChannelMap()

View license
public static LongSparseArray<XmlTvParser.XmlTvChannel> buildChannelMap(ContentResolver resolver, String inputId, List<XmlTvParser.XmlTvChannel> channels) {
    Uri uri = TvContract.buildChannelsUriForInput(inputId);
    String[] projection = { TvContract.Channels._ID, TvContract.Channels.COLUMN_DISPLAY_NUMBER };
    LongSparseArray<XmlTvParser.XmlTvChannel> channelMap = new LongSparseArray<>();
    try (Cursor cursor = resolver.query(uri, projection, null, null, null)) {
        if (cursor == null || cursor.getCount() == 0) {
            return null;
        }
        while (cursor.moveToNext()) {
            long channelId = cursor.getLong(0);
            String channelNumber = cursor.getString(1);
            channelMap.put(channelId, getChannelByNumber(channelNumber, channels));
        }
    } catch (Exception e) {
        Log.d(TAG, "Content provider query: " + Arrays.toString(e.getStackTrace()));
        return null;
    }
    return channelMap;
}

90. TvContractUtils#getPrograms()

View license
public static List<Program> getPrograms(ContentResolver resolver, Uri channelUri) {
    Uri uri = TvContract.buildProgramsUriForChannel(channelUri);
    List<Program> programs = new ArrayList<>();
    // TvProvider returns programs in chronological order by default.
    try (Cursor cursor = resolver.query(uri, null, null, null, null)) {
        if (cursor == null || cursor.getCount() == 0) {
            return programs;
        }
        while (cursor.moveToNext()) {
            programs.add(Program.fromCursor(cursor));
        }
    } catch (Exception e) {
        Log.w(TAG, "Unable to get programs for " + channelUri, e);
    }
    return programs;
}

91. DeleteQuestionService#onHandleIntent()

View license
@Override
public void onHandleIntent(Intent intent) {
    mGoogleApiClient.blockingConnect(CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    Uri dataItemUri = intent.getData();
    if (!mGoogleApiClient.isConnected()) {
        Log.e(TAG, "Failed to update data item " + dataItemUri + " because client is disconnected from Google Play Services");
        return;
    }
    DataApi.DataItemResult dataItemResult = Wearable.DataApi.getDataItem(mGoogleApiClient, dataItemUri).await();
    PutDataMapRequest putDataMapRequest = PutDataMapRequest.createFromDataMapItem(DataMapItem.fromDataItem(dataItemResult.getDataItem()));
    DataMap dataMap = putDataMapRequest.getDataMap();
    dataMap.putBoolean(QUESTION_WAS_DELETED, true);
    PutDataRequest request = putDataMapRequest.asPutDataRequest();
    Wearable.DataApi.putDataItem(mGoogleApiClient, request).await();
    mGoogleApiClient.disconnect();
}

92. iDataORM#addFavor()

Project: android_tv_metro
Source File: iDataORM.java
View license
public static Uri addFavor(Context context, String ns, String res_id, String json) {
    Uri ret = null;
    ContentValues ct = new ContentValues();
    ct.put(FavorCol.RES_ID, res_id);
    ct.put(FavorCol.NS, ns);
    ct.put(FavorCol.VALUE, json);
    ct.put(SettingsCol.ChangeDate, dateToString(new Date()));
    //if exist, update
    if (true == existFavor(context, ns, res_id)) {
        updateFavor(context, ct);
    } else {
        ret = context.getContentResolver().insert(FAVOR_CONTENT_URI, ct);
    }
    return ret;
}

93. iDataORM#addSetting()

Project: android_tv_metro
Source File: iDataORM.java
View license
private static Uri addSetting(Context context, Uri settingUri, String name, String value) {
    Uri ret = null;
    ContentValues ct = new ContentValues();
    ct.put(SettingsCol.Name, name);
    ct.put(SettingsCol.Value, value);
    ct.put(SettingsCol.ChangeDate, dateToString(new Date()));
    //if exist, update
    if (null != getSettingValue(context, settingUri, name)) {
        updateSetting(context, settingUri, name, value);
    } else {
        ret = context.getContentResolver().insert(settingUri, ct);
    }
    return ret;
}

94. FacebookAppLinkResolver#getAndroidTargetFromJson()

View license
private static AppLink.Target getAndroidTargetFromJson(JSONObject targetJson) {
    String packageName = tryGetStringFromJson(targetJson, APP_LINK_TARGET_PACKAGE_KEY, null);
    if (packageName == null) {
        // Package name is mandatory for each Android target
        return null;
    }
    String className = tryGetStringFromJson(targetJson, APP_LINK_TARGET_CLASS_KEY, null);
    String appName = tryGetStringFromJson(targetJson, APP_LINK_TARGET_APP_NAME_KEY, null);
    String targetUrlString = tryGetStringFromJson(targetJson, APP_LINK_TARGET_URL_KEY, null);
    Uri targetUri = null;
    if (targetUrlString != null) {
        targetUri = Uri.parse(targetUrlString);
    }
    return new AppLink.Target(packageName, className, targetUri, appName);
}

95. ForecastFragment#onCreateLoader()

Project: Angani
Source File: ForecastFragment.java
View license
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    // This is called when a new Loader needs to be created.  This
    // fragment only uses one loader, so we don't care about checking the id.
    // To only show current and future dates, filter the query to return weather only for
    // dates after or including today.
    // Sort order:  Ascending, by date.
    String sortOrder = WeatherDbHelper.WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
    String locationSetting = Utility.getPreferredLocation(getActivity());
    Uri weatherForLocationUri = WeatherDbHelper.WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis());
    return new CursorLoader(getActivity(), weatherForLocationUri, FORECAST_COLUMNS, null, null, sortOrder);
}

96. ContentProviderTest#testUpdateNoteFields()

View license
/**
     * Check that updating the flds column works as expected
     */
public void testUpdateNoteFields() {
    final ContentResolver cr = getContext().getContentResolver();
    ContentValues cv = new ContentValues();
    // Change the fields so that the first field is now "newTestValue"
    String[] dummyFields2 = mDummyFields.clone();
    dummyFields2[0] = TEST_FIELD_VALUE;
    for (Uri uri : mCreatedNotes) {
        // Update the flds
        cv.put(FlashCardsContract.Note.FLDS, Utils.joinFields(dummyFields2));
        cr.update(uri, cv, null, null);
        // Query the table again
        Cursor noteCursor = cr.query(uri, FlashCardsContract.Note.DEFAULT_PROJECTION, null, null, null);
        try {
            assertNotNull("Check that there is a valid cursor for detail data after update", noteCursor);
            assertEquals("Check that there is one and only one entry after update", 1, noteCursor.getCount());
            assertTrue("Move to first item in cursor", noteCursor.moveToFirst());
            String[] newFlds = Utils.splitFields(noteCursor.getString(noteCursor.getColumnIndex(FlashCardsContract.Note.FLDS)));
            assertTrue("Check that the flds have been updated correctly", Arrays.equals(newFlds, dummyFields2));
        } finally {
            noteCursor.close();
        }
    }
}

97. ContentProviderTest#testQueryCurrentModel()

View license
/**
     * Check that querying the current model gives a valid result
     */
public void testQueryCurrentModel() {
    final ContentResolver cr = getContext().getContentResolver();
    Uri uri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, FlashCardsContract.Model.CURRENT_MODEL_ID);
    final Cursor modelCursor = cr.query(uri, null, null, null, null);
    assertNotNull(modelCursor);
    try {
        assertEquals("Check that there is exactly one result", 1, modelCursor.getCount());
        assertTrue("Move to beginning of cursor", modelCursor.moveToFirst());
        assertNotNull("Check non-empty field names", modelCursor.getString(modelCursor.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES)));
        assertTrue("Check at least one template", modelCursor.getInt(modelCursor.getColumnIndex(FlashCardsContract.Model.NUM_CARDS)) > 0);
    } finally {
        modelCursor.close();
    }
}

98. ContentProviderTest#testQueryCertainDeck()

View license
/**
     * Test query to specific deck ID
     * @throws Exception
     */
public void testQueryCertainDeck() throws Exception {
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    long deckId = mTestDeckIds[0];
    Uri deckUri = Uri.withAppendedPath(FlashCardsContract.Deck.CONTENT_ALL_URI, Long.toString(deckId));
    Cursor decksCursor = getContext().getContentResolver().query(deckUri, null, null, null, null);
    try {
        if (decksCursor == null || !decksCursor.moveToFirst()) {
            fail("No deck received. Should have delivered deck with id " + deckId);
        } else {
            long returnedDeckID = decksCursor.getLong(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_ID));
            String returnedDeckName = decksCursor.getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_NAME));
            JSONObject realDeck = col.getDecks().get(deckId);
            assertEquals("Check that received deck ID equals real deck ID", deckId, returnedDeckID);
            assertEquals("Check that received deck name equals real deck name", realDeck.getString("name"), returnedDeckName);
        }
    } finally {
        decksCursor.close();
    }
}

99. AddContentApi#getNote()

Project: Anki-Android
Source File: AddContentApi.java
View license
/**
     * Get the contents of a note with known ID
     * @param noteId the ID of the note to find
     * @return object containing the contents of note with noteID
     */
public NoteInfo getNote(long noteId) {
    Uri noteUri = Uri.withAppendedPath(Note.CONTENT_URI, Long.toString(noteId));
    Cursor cursor = mResolver.query(noteUri, PROJECTION, null, null, null);
    if (cursor == null) {
        return null;
    }
    try {
        if (!cursor.moveToNext()) {
            return null;
        }
        return NoteInfo.buildFromCursor(cursor);
    } finally {
        cursor.close();
    }
}

100. AddContentApi#updateNote()

Project: Anki-Android
Source File: AddContentApi.java
View license
private boolean updateNote(long noteId, String[] fields, Set<String> tags) {
    Uri.Builder builder = Note.CONTENT_URI.buildUpon();
    Uri contentUri = builder.appendPath(Long.toString(noteId)).build();
    ContentValues values = new ContentValues();
    if (fields != null) {
        values.put(Note.FLDS, Utils.joinFields(fields));
    }
    if (tags != null) {
        values.put(Note.TAGS, Utils.joinTags(tags));
    }
    int numRowsUpdated = mResolver.update(contentUri, values, null, null);
    // provider doesn't check whether fields actually changed, so just returns number of notes with id == noteId
    return numRowsUpdated > 0;
}