Example usage for android.net Uri getPathSegments

List of usage examples for android.net Uri getPathSegments

Introduction

In this page you can find the example usage for android.net Uri getPathSegments.

Prototype

public abstract List<String> getPathSegments();

Source Link

Document

Gets the decoded path segments.

Usage

From source file:org.ale.openwatch.FeedFragmentActivity.java

private boolean checkIntentForUri(Intent intent) {
    Uri data = intent.getData();
    if (data != null) {
        //String scheme = data.getScheme(); // "openwatch"
        List<String> params = data.getPathSegments();
        String tag = params.get(1); // "police"
        Log.i(TAG, "got tag from url: " + tag);
        if (!mTitleToTabId.containsKey(tag)) {
            addTagOrFeed(tag);/*from   ww  w .  j a v a2s  .  c  o m*/
        }
        mTitleIndicator.setCurrentItem(mTitleToTabId.get(tag.toLowerCase()));
        return true;

    } else if (intent.getExtras() != null && intent.getExtras().containsKey(Constants.FEED_TYPE)) {
        OWFeedType feedType = ((OWFeedType) intent.getExtras().getSerializable(Constants.FEED_TYPE));
        if (feedType == OWFeedType.USER) {
            // Force the user feed to refresh
            RemoteRecordingsListFragment userFrag = ((RemoteRecordingsListFragment) FeedFragmentActivity.this.mTabsAdapter
                    .getItem(mTitleToTabId.get(feedType.toString().toLowerCase())));
            FeedFragmentActivity.this.forceUserFeedRefresh = true;
            //userFrag.didRefreshFeed = false;
            //userFrag.forceRefresh = true;
            Log.i(feedType.toString(), "force refresh feed now!");
        }
        mTitleIndicator.setCurrentItem(mTitleToTabId.get(feedType.toString().toLowerCase()));
        return true;
    }

    if (intent.getBooleanExtra(Constants.VICTORY, false)) {
        View v = getLayoutInflater().inflate(R.layout.dialog_victory, null);
        new AlertDialog.Builder(this).setView(v)
                .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    return false;
}

From source file:com.ichi2.anki.provider.CardContentProvider.java

private Note getNoteFromUri(Uri uri, Collection col) {
    long noteId;//from   ww  w .j a  v  a  2 s.com
    noteId = Long.parseLong(uri.getPathSegments().get(1));
    return col.getNote(noteId);
}

From source file:com.ichi2.anki.provider.CardContentProvider.java

private Card getCardFromUri(Uri uri, Collection col) {
    long noteId;//from ww  w .j  a va 2  s  .c  o  m
    int ord;
    noteId = Long.parseLong(uri.getPathSegments().get(1));
    ord = Integer.parseInt(uri.getPathSegments().get(3));
    return getCard(noteId, ord, col);
}

From source file:org.opendatakit.services.forms.provider.FormsProvider.java

@Override
public synchronized int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) {
    possiblyWaitForContentProviderDebugger();

    List<String> segments = uri.getPathSegments();

    PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs);
    WebLoggerIf logger = WebLogger.getLogger(pf.appName);

    /*/* w  w  w .j  a  v  a2 s.co m*/
     * First, find out what records match this query. Replicate the 
     * ContentValues if there are multiple tableIds/formIds involved
     * and the contentValues do not have formId and tableId specified.
     * 
     * Otherwise, it is an error to specify the tableId or formId in
     * the ContentValues and have those not match the where results.
     * 
     */
    String contentTableId = (values != null && values.containsKey(FormsColumns.TABLE_ID))
            ? values.getAsString(FormsColumns.TABLE_ID)
            : null;
    String contentFormId = (values != null && values.containsKey(FormsColumns.FORM_ID))
            ? values.getAsString(FormsColumns.FORM_ID)
            : null;

    HashMap<FormSpec, HashMap<String, Object>> matchedValues = new HashMap<FormSpec, HashMap<String, Object>>();

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        Cursor c = null;
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, null, pf.whereId, pf.whereIdArgs, null, null, null,
                    null);

            if (c == null) {
                throw new SQLException(
                        "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
            }
            if (c.moveToFirst()) {
                int idxId = c.getColumnIndex(FormsColumns._ID);
                int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID);
                int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID);

                Integer idValue = null;
                String tableIdValue = null;
                String formIdValue = null;

                do {
                    idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId);
                    tableIdValue = CursorUtils.getIndexAsString(c, idxTableId);
                    formIdValue = CursorUtils.getIndexAsString(c, idxFormId);

                    if (contentTableId != null && !contentTableId.equals(tableIdValue)) {
                        throw new SQLException("Modification of tableId for an existing form is prohibited");
                    }
                    if (contentFormId != null && !contentFormId.equals(formIdValue)) {
                        throw new SQLException("Modification of formId for an existing form is prohibited");
                    }

                    HashMap<String, Object> cv = new HashMap<String, Object>();
                    if (values != null) {
                        for (String key : values.keySet()) {
                            cv.put(key, values.get(key));
                        }
                    }
                    cv.put(FormsColumns.TABLE_ID, tableIdValue);
                    cv.put(FormsColumns.FORM_ID, formIdValue);
                    for (int idx = 0; idx < c.getColumnCount(); ++idx) {
                        String colName = c.getColumnName(idx);
                        if (colName.equals(FormsColumns._ID)) {
                            // don't insert the PK
                            continue;
                        }

                        if (c.isNull(idx)) {
                            cv.put(colName, null);
                        } else {
                            // everything else, we control...
                            Class<?> dataType = CursorUtils.getIndexDataType(c, idx);
                            if (dataType == String.class) {
                                cv.put(colName, CursorUtils.getIndexAsString(c, idx));
                            } else if (dataType == Long.class) {
                                cv.put(colName, CursorUtils.getIndexAsType(c, Long.class, idx));
                            } else if (dataType == Double.class) {
                                cv.put(colName, CursorUtils.getIndexAsType(c, Double.class, idx));
                            }
                        }
                    }

                    FormSpec formSpec = patchUpValues(pf.appName, cv);
                    formSpec._id = idValue.toString();
                    formSpec.success = false;
                    matchedValues.put(formSpec, cv);

                } while (c.moveToNext());
            } else {
                // no match on where clause...
                return 0;
            }
        } finally {
            if (c != null && !c.isClosed()) {
                c.close();
            }
        }

        // go through the entries and update the database with these patched-up values...

        for (Entry<FormSpec, HashMap<String, Object>> e : matchedValues.entrySet()) {
            FormSpec fs = e.getKey();
            HashMap<String, Object> cv = e.getValue();

            if (db.update(DatabaseConstants.FORMS_TABLE_NAME, cv, FormsColumns._ID + "=?",
                    new String[] { fs._id }) > 0) {
                fs.success = true;
            }
        }
        db.setTransactionSuccessful();

    } catch (Exception e) {
        logger.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
                            .removeConnection(pf.appName, dbHandleName);
                }
            }
        }
    }

    int failureCount = 0;
    for (FormSpec fs : matchedValues.keySet()) {
        if (fs.success) {
            Uri formUri = Uri
                    .withAppendedPath(
                            Uri.withAppendedPath(Uri.withAppendedPath(
                                    Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId),
                            fs.formId);
            getContext().getContentResolver().notifyChange(formUri, null);
            Uri idUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), fs._id);
            getContext().getContentResolver().notifyChange(idUri, null);
        } else {
            ++failureCount;
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);

    int count = matchedValues.size();
    if (failureCount != 0) {
        throw new SQLiteException(
                "Unable to update all forms (" + (count - failureCount) + " of " + count + " updated)");
    }
    return count;
}

From source file:org.totschnig.myexpenses.dialog.DialogUtils.java

/**
 * @return display name for document stored at mUri.
 * Returns null if accessing mUri raises {@link SecurityException}
 *//*from  w w w  .j a v a 2s. c om*/
@SuppressLint("NewApi")
public static String getDisplayName(Uri uri) {

    if (!"file".equalsIgnoreCase(uri.getScheme()) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // The query, since it only applies to a single document, will only return
        // one row. There's no need to filter, sort, or select fields, since we want
        // all fields for one document.
        try {
            Cursor cursor = MyApplication.getInstance().getContentResolver().query(uri, null, null, null, null,
                    null);

            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        // Note it's called "Display Name".  This is
                        // provider-specific, and might not necessarily be the file name.
                        int columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                        if (columnIndex != -1) {
                            String displayName = cursor.getString(columnIndex);
                            if (displayName != null) {
                                return displayName;
                            }
                        }
                    }
                } catch (Exception e) {
                } finally {
                    cursor.close();
                }
            }
        } catch (SecurityException e) {
            //this can happen if the user has restored a backup and
            //we do not have a persistable permision
            //return null;
        }
    }
    List<String> filePathSegments = uri.getPathSegments();
    if (!filePathSegments.isEmpty()) {
        return filePathSegments.get(filePathSegments.size() - 1);
    } else {
        return "UNKNOWN";
    }
}

From source file:com.androidclub.source.XmlDocumentProvider.java

/**
 * Creates an XmlPullParser for the provided local resource. Can be overloaded to provide your
 * own parser./*from w ww .j  a  v a2  s  .  com*/
 * @param resourceUri A fully qualified resource name referencing a local XML resource.
 * @return An XmlPullParser on this resource.
 */
protected XmlPullParser getResourceXmlPullParser(Uri resourceUri) {
    //OpenResourceIdResult resourceId;
    try {
        String authority = resourceUri.getAuthority();
        Resources r;
        if (TextUtils.isEmpty(authority)) {
            throw new FileNotFoundException("No authority: " + resourceUri);
        } else {
            try {
                r = getContext().getPackageManager().getResourcesForApplication(authority);
            } catch (NameNotFoundException ex) {
                throw new FileNotFoundException("No package found for authority: " + resourceUri);
            }
        }
        List<String> path = resourceUri.getPathSegments();
        if (path == null) {
            throw new FileNotFoundException("No path: " + resourceUri);
        }
        int len = path.size();
        int id;
        if (len == 1) {
            try {
                id = Integer.parseInt(path.get(0));
            } catch (NumberFormatException e) {
                throw new FileNotFoundException("Single path segment is not a resource ID: " + resourceUri);
            }
        } else if (len == 2) {
            id = r.getIdentifier(path.get(1), path.get(0), authority);
        } else {
            throw new FileNotFoundException("More than two path segments: " + resourceUri);
        }
        if (id == 0) {
            throw new FileNotFoundException("No resource found for: " + resourceUri);
        }

        return r.getXml(id);
    } catch (FileNotFoundException e) {
        Log.w(LOG_TAG, "XML resource not found: " + resourceUri.toString(), e);
        return null;
    }
}

From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_item_detail);
    ButterKnife.bind(this);
    setSupportActionBar(mToolbar);//w  w  w .  j  a  v a  2  s.c o  m

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    mSlidingPanel.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN);
    SlidingUpPanelLayout.LayoutParams lp = ((SlidingUpPanelLayout.LayoutParams) mCommentComposerContainer
            .getLayoutParams());
    if (lp != null) {
        lp.topMargin += UIUtil.getStatusBarHeight(ItemDetailActivity.this) + mToolbar.getMinimumHeight();
        mCommentComposerContainer.setLayoutParams(lp);
    }

    mSlidingPanel.setScrollableViewHelper(new NestedScrollableViewHelper());
    mSlidingPanel.setPanelSlideListener(new PanelSlideListenerAdapter() {
        @Override
        public void onPanelCollapsed(View panel) {
            ImeUtil.hideIme(panel);
        }

        @Override
        public void onPanelAnchored(View panel) {
            ImeUtil.hideIme(panel);
        }

        @Override
        public void onPanelHidden(View panel) {
            ImeUtil.hideIme(panel);
        }
    });

    mCommentComposer.addOnPageChangeListener(mCommentComposerPageChange);
    mComposerTabs.setupWithViewPager(mCommentComposer);

    // empty title at start
    setTitle("");

    trySetupMenuDrawerLayout();
    trySetupContentView();
    trySetupCommentView();

    mAppBarLayout.addOnOffsetChangedListener(mOffsetChangedListener);

    mArticleDescription.setClickable(true);
    mArticleDescription.setMovementMethod(LinkMovementMethod.getInstance());
    // dynamically update padding
    mArticleName.setPadding(mArticleName.getPaddingLeft(),
            mArticleName.getPaddingTop() + UIUtil.getStatusBarHeight(this), mArticleName.getPaddingRight(),
            mArticleName.getPaddingBottom());

    TypedValue typedValue = new TypedValue();
    mToolbar.getContext().getTheme().resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
    int titleColorId = typedValue.resourceId;
    mTitleColorSpan = new AlphaForegroundColorSpan(ContextCompat.getColor(this, titleColorId));

    typedValue = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
    mCommentThreadColor = ContextCompat.getColor(this, typedValue.resourceId);

    Uri data = getIntent().getData();
    if (data != null) {
        List<String> paths = data.getPathSegments();
        if (!UIUtil.isEmpty(paths)) {
            Iterator<String> iterator = paths.iterator();
            while (iterator.hasNext()) {
                if ("items".equals(iterator.next())) {
                    mItemUuid = iterator.next();
                    break;
                }
            }
        }
    }

    Article article = mRealm.where(Article.class).equalTo("id", mItemUuid).findFirst();
    if (article != null) {
        EventBus.getDefault().post(new ItemDetailEvent(getClass().getSimpleName(), true, null, article));
    }

    ApiClient.isStocked(mItemUuid).enqueue(mStockStatusResponse);
}

From source file:org.mariotaku.twidere.provider.TwidereDataProvider.java

@Override
public int delete(final Uri uri, final String selection, final String[] selectionArgs) {
    try {//from  w  w w .  j a  v  a 2  s. c o  m
        final int table_id = getTableId(uri);
        final String table = getTableNameById(table_id);
        checkWritePermission(table_id, table);
        if (table_id == VIRTUAL_TABLE_ID_NOTIFICATIONS) {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() != 2)
                return 0;
            clearNotification(parseInt(segments.get(1)));
        }
        switch (table_id) {
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
        case TABLE_ID_DIRECT_MESSAGES:
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRY:
            return 0;
        }
        if (table == null)
            return 0;
        final int result = mDatabase.delete(table, selection, selectionArgs);
        if (result > 0) {
            onDatabaseUpdated(uri);
        }
        return result;
    } catch (final SQLException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.thomnichols.android.gmarks.GmarksProvider.java

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    int count;/*from w ww .  j  av  a2s  .  c o m*/
    switch (sUriMatcher.match(uri)) {
    case BOOKMARKS_URI:
        count = db.delete(BOOKMARKS_TABLE_NAME, where, whereArgs);
        break;

    case BOOKMARK_ID_URI:
        String noteId = uri.getPathSegments().get(1);
        count = db.delete(BOOKMARKS_TABLE_NAME,
                Bookmark.Columns._ID + "=" + noteId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
                whereArgs);
        break;
    // TODO delete item from text search!

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

From source file:org.runbuddy.tomahawk.activities.TomahawkMainActivity.java

private void handleIntent(Intent intent) {
    if (MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH.equals(intent.getAction())) {
        intent.setAction(null);//from w  ww.j  av a  2s .co  m
        String playbackManagerId = getSupportMediaController().getExtras()
                .getString(PlaybackService.EXTRAS_KEY_PLAYBACKMANAGER);
        PlaybackManager playbackManager = PlaybackManager.getByKey(playbackManagerId);
        MediaPlayIntentHandler intentHandler = new MediaPlayIntentHandler(
                getSupportMediaController().getTransportControls(), playbackManager);
        intentHandler.mediaPlayFromSearch(intent.getExtras());
    }
    if ("com.google.android.gms.actions.SEARCH_ACTION".equals(intent.getAction())) {
        intent.setAction(null);
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (query != null && !query.isEmpty()) {
            DatabaseHelper.get().addEntryToSearchHistory(query);
            Bundle bundle = new Bundle();
            bundle.putString(TomahawkFragment.QUERY_STRING, query);
            bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC);
            FragmentUtils.replace(TomahawkMainActivity.this, SearchPagerFragment.class, bundle);
        }
    }
    if (SHOW_PLAYBACKFRAGMENT_ON_STARTUP.equals(intent.getAction())) {
        intent.setAction(null);
        // if this Activity is being shown after the user clicked the notification
        if (mSlidingUpPanelLayout != null) {
            mSlidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
        }
    }
    if (intent.hasExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)) {
        intent.removeExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
        Bundle bundle = new Bundle();
        bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC_SMALL);
        FragmentUtils.replace(this, PreferencePagerFragment.class, bundle);
    }

    if (intent.getData() != null) {
        final Uri data = intent.getData();
        intent.setData(null);
        List<String> pathSegments = data.getPathSegments();
        String host = data.getHost();
        String scheme = data.getScheme();
        if ((scheme != null && (scheme.equals("spotify") || scheme.equals("tomahawk"))) || (host != null
                && (host.contains("spotify.com") || host.contains("hatchet.is") || host.contains("toma.hk")
                        || host.contains("beatsmusic.com") || host.contains("deezer.com")
                        || host.contains("rdio.com") || host.contains("soundcloud.com")))) {
            PipeLine.get().lookupUrl(data.toString());
        } else if ((pathSegments != null && pathSegments.get(pathSegments.size() - 1).endsWith(".xspf"))
                || (intent.getType() != null && intent.getType().equals("application/xspf+xml"))) {
            TomahawkRunnable r = new TomahawkRunnable(TomahawkRunnable.PRIORITY_IS_INFOSYSTEM_HIGH) {
                @Override
                public void run() {
                    Playlist pl = XspfParser.parse(data);
                    if (pl != null) {
                        final Bundle bundle = new Bundle();
                        bundle.putString(TomahawkFragment.PLAYLIST, pl.getCacheKey());
                        bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE,
                                ContentHeaderFragment.MODE_HEADER_DYNAMIC);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class,
                                        bundle);
                            }
                        });
                    }
                }
            };
            ThreadManager.get().execute(r);
        } else if (pathSegments != null && (pathSegments.get(pathSegments.size() - 1).endsWith(".axe")
                || pathSegments.get(pathSegments.size() - 1).endsWith(".AXE"))) {
            InstallPluginConfigDialog dialog = new InstallPluginConfigDialog();
            Bundle args = new Bundle();
            args.putString(InstallPluginConfigDialog.PATH_TO_AXE_URI_STRING, data.toString());
            dialog.setArguments(args);
            dialog.show(getSupportFragmentManager(), null);
        } else {
            String albumName;
            String trackName;
            String artistName;
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(this, data);
                albumName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
                artistName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
                trackName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
                retriever.release();
            } catch (Exception e) {
                Log.e(TAG, "handleIntent: " + e.getClass() + ": " + e.getLocalizedMessage());
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        String msg = TomahawkApp.getContext().getString(R.string.invalid_file);
                        Toast.makeText(TomahawkApp.getContext(), msg, Toast.LENGTH_LONG).show();
                    }
                });
                return;
            }
            if (TextUtils.isEmpty(trackName) && pathSegments != null) {
                trackName = pathSegments.get(pathSegments.size() - 1);
            }
            Query query = Query.get(trackName, albumName, artistName, false);
            Result result = Result.get(data.toString(), query.getBasicTrack(),
                    UserCollectionStubResolver.get());
            float trackScore = query.howSimilar(result);
            query.addTrackResult(result, trackScore);
            Bundle bundle = new Bundle();
            List<Query> queries = new ArrayList<>();
            queries.add(query);
            Playlist playlist = Playlist.fromQueryList(IdGenerator.getSessionUniqueStringId(), "", "", queries);
            playlist.setFilled(true);
            playlist.setName(artistName + " - " + trackName);
            bundle.putString(TomahawkFragment.PLAYLIST, playlist.getCacheKey());
            bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC);
            FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle);
        }
    }
}