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:com.example.nitish.welcomapp.activitypt.ElementDetailsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    final boolean darkTheme = PreferenceUtils.getPrefDarkTheme();
    setTheme(darkTheme ? R.style.DarkTheme : R.style.LightTheme);

    super.onCreate(savedInstanceState);

    ActionBarCompat.setDisplayHomeAsUpEnabled(this, true);

    if (savedInstanceState == null) {
        final Intent intent = getIntent();
        Fragment fragment = null;//from   w  w  w  .ja v  a2  s .  c om
        if (intent.hasExtra(EXTRA_ATOMIC_NUMBER)) {
            fragment = ElementDetailsFragment.getInstance(intent.getIntExtra(EXTRA_ATOMIC_NUMBER, 0));
        } else if (getIntent().getData() != null) {
            final Uri uri = getIntent().getData();
            if (uri.getHost().equals("element")) {
                final String path = uri.getPathSegments().get(0);
                if (TextUtils.isDigitsOnly(path)) {
                    try {
                        fragment = ElementDetailsFragment
                                .getInstance(Integer.parseInt(uri.getPathSegments().get(0)));
                    } catch (NumberFormatException e) {
                        Log.w(TAG, "Invalid atomic number");
                    }
                } else {
                    fragment = ElementDetailsFragment.getInstance(path);
                }
            }
        }
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit();
        }
    }
}

From source file:com.applozic.mobicommons.file.FileUtils.java

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>/*from   w w w .  ja v a  2s.  c o  m*/
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 *
 * @param context The context.
 * @param uri     The Uri to query.
 * @author paulburke
 * @see #isLocal(String)
 * @see #getFile(android.content.Context, android.net.Uri)
 */

public static String getPath(final Context context, final Uri uri) {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: "
                        + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme()
                        + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString());

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // LocalStorageProvider
        if (isLocalStorageDocument(uri)) {
            // The path is the id
            return DocumentsContract.getDocumentId(uri);
        }
        // ExternalStorageProvider
        else if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.android.messaging.datamodel.BugleNotifications.java

/**
 * Returns the displayPhotoUri from the avatar URI, or null if avatar URI
 * does not have a displayPhotoUri.//from  w w  w. j  ava2  s. c o m
 */
private static Uri getDisplayPhotoUri(final Uri avatarUri) {
    final Uri thumbnailUri = getThumbnailUri(avatarUri);
    if (thumbnailUri == null) {
        return null;
    }
    final List<String> originalPaths = thumbnailUri.getPathSegments();
    final int originalPathsSize = originalPaths.size();
    final StringBuilder newPathBuilder = new StringBuilder();
    // Change content://com.android.contacts/contacts("_corp")/123/photo to
    // content://com.android.contacts/contacts("_corp")/123/display_photo
    for (int i = 0; i < originalPathsSize; i++) {
        newPathBuilder.append('/');
        if (i == 2) {
            newPathBuilder.append(ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
        } else {
            newPathBuilder.append(originalPaths.get(i));
        }
    }
    return thumbnailUri.buildUpon().path(newPathBuilder.toString()).build();
}

From source file:cn.code.notes.gtask.data.SqlConn.java

public void commit(long noteId, boolean validateVersion, long version) {

    if (mIsCreate) {
        if (mId == INVALID_ID && mDiffDataValues.containsKey(ConnectColumns.NOTE_ID)) {
            mDiffDataValues.remove(ConnectColumns.NOTE_ID);
        }//w ww . j a v  a  2 s  . c  o  m

        mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
        Uri uri = mContentResolver.insert(Notes.CONTENT_CONN_URI, mDiffDataValues);
        try {
            mId = Long.valueOf(uri.getPathSegments().get(1));
        } catch (NumberFormatException e) {
            Log.e(TAG, "Get note id error :" + e.toString());
            throw new ActionFailureException("create note failed");
        }
    } else {
        if (mDiffDataValues.size() > 0) {
            int result = 0;
            if (!validateVersion) {
                result = mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_CONN_URI, mId),
                        mDiffDataValues, null, null);
            } else {
                result = mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_CONN_URI, mId),
                        mDiffDataValues,
                        " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + " WHERE "
                                + NoteColumns.VERSION + "=?)",
                        new String[] { String.valueOf(noteId), String.valueOf(version) });
            }
            if (result == 0) {
                Log.w(TAG, "there is no update. maybe user updates note when syncing");
            }
        }
    }

    mDiffDataValues.clear();
    mIsCreate = false;
}

From source file:com.android.quicksearchbox.google.GoogleSuggestionProvider.java

/**
 * Gets the search text from a uri.//www.  j  ava 2 s.  c  o  m
 */
private String getQuery(Uri uri) {
    if (uri.getPathSegments().size() > 1) {
        return uri.getLastPathSegment();
    } else {
        return "";
    }
}

From source file:cn.code.notes.gtask.data.SqlData.java

public void commit(long noteId, boolean validateVersion, long version) {

    if (mIsCreate) {
        if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
            mDiffDataValues.remove(DataColumns.ID);
        }/*  w  w w.  j  a  v  a  2s . co m*/

        mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
        Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
        try {
            mDataId = Long.valueOf(uri.getPathSegments().get(1));
        } catch (NumberFormatException e) {
            Log.e(TAG, "Get note id error :" + e.toString());
            throw new ActionFailureException("create note failed");
        }
    } else {
        if (mDiffDataValues.size() > 0) {
            int result = 0;
            if (!validateVersion) {
                result = mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, mDataId),
                        mDiffDataValues, null, null);
            } else {
                result = mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, mDataId),
                        mDiffDataValues,
                        " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + " WHERE "
                                + NoteColumns.VERSION + "=?)",
                        new String[] { String.valueOf(noteId), String.valueOf(version) });
            }
            if (result == 0) {
                Log.w(TAG, "there is no update. maybe user updates note when syncing");
            }
        }
    }

    mDiffDataValues.clear();
    mIsCreate = false;
}

From source file:com.xabber.android.ui.ContactViewer.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
        // View information about contact from system contact list
        Uri data = getIntent().getData();
        if (data != null && "content".equals(data.getScheme())) {
            List<String> segments = data.getPathSegments();
            if (segments.size() == 2 && "data".equals(segments.get(0))) {
                Long id;/*from  www.  j  av  a  2  s. co  m*/
                try {
                    id = Long.valueOf(segments.get(1));
                } catch (NumberFormatException e) {
                    id = null;
                }
                if (id != null)
                    // FIXME: Will be empty while application is loading
                    for (RosterContact rosterContact : RosterManager.getInstance().getContacts())
                        if (id.equals(rosterContact.getViewId())) {
                            account = rosterContact.getAccount();
                            bareAddress = rosterContact.getUser();
                            break;
                        }
            }
        }
    } else {
        account = getAccount(getIntent());
        bareAddress = Jid.getBareAddress(getUser(getIntent()));
    }

    if (bareAddress != null && bareAddress.equalsIgnoreCase(GroupManager.IS_ACCOUNT)) {
        bareAddress = Jid.getBareAddress(AccountManager.getInstance().getAccount(account).getRealJid());
    }

    if (account == null || bareAddress == null) {
        Application.getInstance().onError(R.string.ENTRY_IS_NOT_FOUND);
        finish();
        return;
    }

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.scrollable_container, ContactVcardViewerFragment.newInstance(account, bareAddress))
                .commit();
    }

    contactTitleExpandableToolbarInflater = new ContactTitleExpandableToolbarInflater(this);
    AbstractContact bestContact = RosterManager.getInstance().getBestContact(account, bareAddress);
    contactTitleExpandableToolbarInflater.onCreate(bestContact);

    View contactTitleView = findViewById(R.id.expandable_contact_title);
    contactTitleView.findViewById(R.id.status_icon).setVisibility(View.GONE);
    contactTitleView.findViewById(R.id.status_text).setVisibility(View.GONE);
    contactNameView = (TextView) contactTitleView.findViewById(R.id.name);

    Toolbar toolbar = contactTitleExpandableToolbarInflater.getToolbar();
    toolbar.setNavigationIcon(R.drawable.ic_arrow_left_white_24dp);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavUtils.navigateUpFromSameTask(ContactViewer.this);
        }
    });
}

From source file:org.coocood.vcontentprovider.VContentProvider.java

private String getIdPath(Uri uri) {
    List<String> paths = uri.getPathSegments();
    if (paths.size() == 1) {
        return null;
    } else if (paths.size() == 2) {
        String idPath = paths.get(1);
        try {//www . j  av a2 s.  c  o m
            Long.parseLong(idPath);
            return idPath;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    } else {
        throw new IllegalArgumentException("Unknown URI " + uri);
    }
}

From source file:com.xandy.calendar.EventInfoActivity.java

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    // Get the info needed for the fragment
    Intent intent = getIntent();/*  w  ww . j  a  v a2s .  com*/
    int attendeeResponse = 0;
    mEventId = -1;
    boolean isDialog = false;
    ArrayList<ReminderEntry> reminders = null;

    if (icicle != null) {
        mEventId = icicle.getLong(EventInfoFragment.BUNDLE_KEY_EVENT_ID);
        mStartMillis = icicle.getLong(EventInfoFragment.BUNDLE_KEY_START_MILLIS);
        mEndMillis = icicle.getLong(EventInfoFragment.BUNDLE_KEY_END_MILLIS);
        attendeeResponse = icicle.getInt(EventInfoFragment.BUNDLE_KEY_ATTENDEE_RESPONSE);
        isDialog = icicle.getBoolean(EventInfoFragment.BUNDLE_KEY_IS_DIALOG);

        reminders = Utils.readRemindersFromBundle(icicle);
    } else if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
        mStartMillis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, 0);
        mEndMillis = intent.getLongExtra(EXTRA_EVENT_END_TIME, 0);
        attendeeResponse = intent.getIntExtra(ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE);
        Uri data = intent.getData();
        if (data != null) {
            try {
                List<String> pathSegments = data.getPathSegments();
                int size = pathSegments.size();
                if (size > 2 && "EventTime".equals(pathSegments.get(2))) {
                    // Support non-standard VIEW intent format:
                    //dat = content://com.android.calendar/events/[id]/EventTime/[start]/[end]
                    mEventId = Long.parseLong(pathSegments.get(1));
                    if (size > 4) {
                        mStartMillis = Long.parseLong(pathSegments.get(3));
                        mEndMillis = Long.parseLong(pathSegments.get(4));
                    }
                } else {
                    mEventId = Long.parseLong(data.getLastPathSegment());
                }
            } catch (NumberFormatException e) {
                if (mEventId == -1) {
                    // do nothing here , deal with it later
                } else if (mStartMillis == 0 || mEndMillis == 0) {
                    // Parsing failed on the start or end time , make sure the times were not
                    // pulled from the intent's extras and reset them.
                    mStartMillis = 0;
                    mEndMillis = 0;
                }
            }
        }
    }

    if (mEventId == -1) {
        Log.w(TAG, "No event id");
        Toast.makeText(this, R.string.event_not_found, Toast.LENGTH_SHORT).show();
        finish();
    }

    // If we do not support showing full screen event info in this configuration,
    // close the activity and show the event in AllInOne.
    Resources res = getResources();
    if (!res.getBoolean(R.bool.agenda_show_event_info_full_screen)
            && !res.getBoolean(R.bool.show_event_info_full_screen)) {
        CalendarController.getInstance(this).launchViewEvent(mEventId, mStartMillis, mEndMillis,
                attendeeResponse);
        finish();
        return;
    }

    setContentView(R.layout.simple_frame_layout);

    // Get the fragment if exists
    mInfoFragment = (EventInfoFragment) getSupportFragmentManager().findFragmentById(R.id.main_frame);

    // Remove the application title
    ActionBar bar = getActionBar();
    if (bar != null) {
        bar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
    }

    // Create a new fragment if none exists
    if (mInfoFragment == null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        mInfoFragment = new EventInfoFragment(this, mEventId, mStartMillis, mEndMillis, attendeeResponse,
                isDialog,
                (isDialog ? EventInfoFragment.DIALOG_WINDOW_STYLE : EventInfoFragment.FULL_WINDOW_STYLE),
                reminders);
        ft.replace(R.id.main_frame, mInfoFragment);
        ft.commit();
    }
}

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

/**
 * Process current intent/*w w w. jav a 2  s .c  o  m*/
 *
 * @param intent The Intent to process
 * @param coldStart first start of this Activity or be called from onNewIntent
 */
private void handleIntent(Intent intent, boolean coldStart) {
    if (intent != null) {
        Uri data = intent.getData();
        if (data != null) {
            List<String> paths = data.getPathSegments();
            if (!UIUtil.isEmpty(paths)) {
                Iterator<String> iterator = paths.iterator();
                while (iterator.hasNext()) {
                    if ("tags".equals(iterator.next())) {
                        mTagId = iterator.next();
                        break;
                    }
                }
            }
        }

        ((State) mState).tagName = mTagId;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, TagItemsFragment.newInstance(mTagId));
        // Add fragment to backstack only when that Fragment is added from current Activity
        if (!coldStart) {
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }
}