Example usage for android.net Uri getLastPathSegment

List of usage examples for android.net Uri getLastPathSegment

Introduction

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

Prototype

@Nullable
public abstract String getLastPathSegment();

Source Link

Document

Gets the decoded last segment in the path.

Usage

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getImageAbsolutePath19(Activity context, Uri imageUri) {
    if (context == null || imageUri == null)
        return null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
            && DocumentsContract.isDocumentUri(context, imageUri)) {
        if (isExternalStorageDocument(imageUri)) {
            String docId = DocumentsContract.getDocumentId(imageUri);
            String[] split = docId.split(":");
            String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }/*from w w w  .  j ava  2s . c om*/
        } else if (isDownloadsDocument(imageUri)) {
            String id = DocumentsContract.getDocumentId(imageUri);
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        } else if (isMediaDocument(imageUri)) {
            String docId = DocumentsContract.getDocumentId(imageUri);
            String[] split = docId.split(":");
            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;
            }
            String selection = MediaStore.Images.Media._ID + "=?";
            String[] selectionArgs = new String[] { split[1] };
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }

    // MediaStore (and general)
    if ("content".equalsIgnoreCase(imageUri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(imageUri))
            return imageUri.getLastPathSegment();
        return getDataColumn(context, imageUri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
        return imageUri.getPath();
    }
    return null;
}

From source file:com.odoo.core.orm.OModel.java

public int insert(OValues values) {
    Uri uri = mContext.getContentResolver().insert(uri(), values.toContentValues());
    if (uri != null) {
        return Integer.parseInt(uri.getLastPathSegment());
    }/*from w ww .j  av  a  2s.c  om*/
    return INVALID_ROW_ID;
}

From source file:com.aengbee.android.leanback.ui.PlaybackOverlayCustomFragment.java

private VideoPlayer.RendererBuilder getRendererBuilder() {
    String userAgent = Util.getUserAgent(getActivity(), "ExoVideoPlayer");
    Uri contentUri = Uri.parse(mSelectedVideo.videoUrl);
    int contentType = Util.inferContentType(contentUri.getLastPathSegment());

    switch (contentType) {
    case Util.TYPE_OTHER: {
        return new ExtractorRendererBuilder(getActivity(), userAgent, contentUri);
    }//from w w  w .j a va 2s. co  m
    default: {
        throw new IllegalStateException("Unsupported type: " + contentType);
    }
    }
}

From source file:org.totschnig.myexpenses.MyApplication.java

/**
 * check if we already have a calendar in Account {@link #PLANNER_ACCOUNT_NAME}
 * of type {@link CalendarContractCompat#ACCOUNT_TYPE_LOCAL} with name
 * {@link #PLANNER_ACCOUNT_NAME} if yes use it, otherwise create it
 * /*w  w w . ja  v a 2s . c  o m*/
 * @return true if we have configured a useable calendar
 * @param persistToSharedPref if true id of the created calendar is stored in preferences
 */
public String createPlanner(boolean persistToSharedPref) {
    Uri.Builder builder = Calendars.CONTENT_URI.buildUpon();
    String plannerCalendarId;
    builder.appendQueryParameter(Calendars.ACCOUNT_NAME, PLANNER_ACCOUNT_NAME);
    builder.appendQueryParameter(Calendars.ACCOUNT_TYPE, CalendarContractCompat.ACCOUNT_TYPE_LOCAL);
    builder.appendQueryParameter(CalendarContractCompat.CALLER_IS_SYNCADAPTER, "true");
    Uri calendarUri = builder.build();
    Cursor c = getContentResolver().query(calendarUri, new String[] { Calendars._ID }, Calendars.NAME + " = ?",
            new String[] { PLANNER_CALENDAR_NAME }, null);
    if (c == null) {
        AcraHelper.report(new Exception("Searching for planner calendar failed, Calendar app not installed?"));
        return INVALID_CALENDAR_ID;
    }
    if (c.moveToFirst()) {
        plannerCalendarId = String.valueOf(c.getLong(0));
        Log.i(TAG, "found a preexisting calendar: " + plannerCalendarId);
        c.close();
    } else {
        c.close();
        ContentValues values = new ContentValues();
        values.put(Calendars.ACCOUNT_NAME, PLANNER_ACCOUNT_NAME);
        values.put(Calendars.ACCOUNT_TYPE, CalendarContractCompat.ACCOUNT_TYPE_LOCAL);
        values.put(Calendars.NAME, PLANNER_CALENDAR_NAME);
        values.put(Calendars.CALENDAR_DISPLAY_NAME, getString(R.string.plan_calendar_name));
        values.put(Calendars.CALENDAR_COLOR, getResources().getColor(R.color.appDefault));
        values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER);
        values.put(Calendars.OWNER_ACCOUNT, "private");
        Uri uri;
        try {
            uri = getContentResolver().insert(calendarUri, values);
        } catch (IllegalArgumentException e) {
            AcraHelper.report(e);
            return INVALID_CALENDAR_ID;
        }
        if (uri == null) {
            AcraHelper.report(new Exception("Inserting planner calendar failed, uri is null"));
            return INVALID_CALENDAR_ID;
        }
        plannerCalendarId = uri.getLastPathSegment();
        if (plannerCalendarId == null || plannerCalendarId.equals("0")) {
            AcraHelper.report(new Exception(String.format(Locale.US,
                    "Inserting planner calendar failed, last path segment is %s", plannerCalendarId)));
            return INVALID_CALENDAR_ID;
        }
        Log.i(TAG, "successfully set up new calendar: " + plannerCalendarId);
    }
    if (persistToSharedPref) {
        // onSharedPreferenceChanged should now trigger initPlanner
        PrefKey.PLANNER_CALENDAR_ID.putString(plannerCalendarId);
    }
    return plannerCalendarId;
}

From source file:com.example.android.cloudnotes.ui.HomeActivity.java

/**
 * This method controls both fragments, instructing them to display a
 * certain note.//from  ww w. ja  v  a 2s .c o m
 * 
 * @param noteUri The {@link Uri} of the note to show. To create a new note,
 *            pass {@code null}.
 */
private void showNote(final Uri noteUri) {

    if (mTwoPaneView) {
        // check if the NoteEditFragment has been added
        FragmentManager fm = getFragmentManager();
        NoteEditFragment edit = (NoteEditFragment) fm.findFragmentByTag(NOTE_EDIT_TAG);
        final boolean editNoteAdded = (edit != null);

        if (editNoteAdded) {
            if (edit.mCurrentNote != null && edit.mCurrentNote.equals(noteUri)) {
                // clicked on the currently selected note
                return;
            }

            NoteEditFragment editFrag = (NoteEditFragment) fm.findFragmentByTag(NOTE_EDIT_TAG);
            if (noteUri != null) {
                // load an existing note
                editFrag.loadNote(noteUri);
                NoteListFragment list = (NoteListFragment) fm.findFragmentById(R.id.list);
                list.setActivatedNote(Long.valueOf(noteUri.getLastPathSegment()));
            } else {
                // creating a new note - clear the form & list
                // activation
                if (editNoteAdded) {
                    editFrag.clear();
                }
                NoteListFragment list = (NoteListFragment) fm.findFragmentById(R.id.list);
                list.clearActivation();
            }
        } else {
            // add the NoteEditFragment to the container
            FragmentTransaction ft = fm.beginTransaction();
            edit = new NoteEditFragment();
            ft.add(R.id.note_detail_container, edit, NOTE_EDIT_TAG);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft.commit();
            edit.loadNote(noteUri);
        }
    } else {
        startActivity(new Intent(NoteEditFragment.ACTION_VIEW_NOTE, noteUri));
    }
}

From source file:com.bluros.updater.UpdatesSettings.java

@Override
protected void onStart() {
    super.onStart();

    // Determine if there are any in-progress downloads
    mDownloadId = mPrefs.getLong(Constants.DOWNLOAD_ID, -1);
    if (mDownloadId >= 0) {
        Cursor c = mDownloadManager.query(new DownloadManager.Query().setFilterById(mDownloadId));
        if (c == null || !c.moveToFirst()) {
            Toast.makeText(this, R.string.download_not_found, Toast.LENGTH_LONG).show();
        } else {/*from   w w w  . j ava2s  .c  o  m*/
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            Uri uri = Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI)));
            if (status == DownloadManager.STATUS_PENDING || status == DownloadManager.STATUS_RUNNING
                    || status == DownloadManager.STATUS_PAUSED) {
                mDownloadFileName = uri.getLastPathSegment();
            }
        }
        if (c != null) {
            c.close();
        }
    }
    if (mDownloadId < 0 || mDownloadFileName == null) {
        resetDownloadState();
    }

    requestUpdateLayout();

    IntentFilter filter = new IntentFilter(UpdateCheckService.ACTION_CHECK_FINISHED);
    filter.addAction(DownloadReceiver.ACTION_DOWNLOAD_STARTED);
    registerReceiver(mReceiver, filter);

    checkForDownloadCompleted(getIntent());
    setIntent(null);
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

private boolean sendDisasterPhoto(Cursor c) throws JSONException {
    String photoFileUri = c.getString(c.getColumnIndex(Tweets.COL_MEDIA_URIS));
    SDCardHelper sdCardHelper = new SDCardHelper();
    String encodedPhoto = sdCardHelper.getImageAsBas64Jpeg(photoFileUri, MAX_IMAGE_DIMENSIONS_PX);
    JSONObject toSendPhoto = new JSONObject("{\"image\":\"" + encodedPhoto + "\"}");
    toSendPhoto.put(TYPE, MESSAGE_TYPE_PHOTO);
    String userID = String.valueOf(c.getLong(c.getColumnIndex(TwitterUsers.COL_TWITTER_USER_ID)));
    toSendPhoto.put("userID", userID);
    Uri uri = Uri.parse(photoFileUri);
    String photoFileName = uri.getLastPathSegment();
    Log.d(TAG, "photoFileName:+ " + photoFileName);
    toSendPhoto.put("photoName", photoFileName);
    bluetoothHelper.write(toSendPhoto.toString());
    return true;/*  w  w  w  .  j a v a  2  s .  c  o  m*/
}

From source file:com.yeldi.yeldibazaar.AppDetails.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("lightTheme", false))
        setTheme(R.style.AppThemeLight);

    super.onCreate(savedInstanceState);
    ActionBarCompat abCompat = ActionBarCompat.create(this);
    abCompat.setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.appdetails);

    Intent i = getIntent();//  w w  w . j av a2 s.c o  m
    appid = "";
    Uri data = getIntent().getData();
    if (data != null) {
        if (data.isHierarchical()) {
            if (data.getHost().equals("details")) {
                // market://details?id=app.id
                appid = data.getQueryParameter("id");
            } else {
                // https://f-droid.org/app/app.id
                appid = data.getLastPathSegment();
            }
        } else {
            // fdroid.app:app.id (old scheme)
            appid = data.getEncodedSchemeSpecificPart();
        }
        Log.d("FDroid", "AppDetails launched from link, for '" + appid + "'");
    } else if (!i.hasExtra("appid")) {
        Log.d("FDroid", "No application ID in AppDetails!?");
    } else {
        appid = i.getStringExtra("appid");
    }

    // Set up the list...
    headerView = new LinearLayout(this);
    ListView lv = (ListView) findViewById(android.R.id.list);
    lv.addHeaderView(headerView);
    ApkListAdapter la = new ApkListAdapter(this, null);
    setListAdapter(la);

    mPm = getPackageManager();
    // Get the preferences we're going to use in this Activity...
    AppDetails old = (AppDetails) getLastNonConfigurationInstance();
    if (old != null) {
        copyState(old);
    } else {
        if (!reset()) {
            finish();
            return;
        }
        resetRequired = false;
    }
    startViews();

}

From source file:org.xbmc.kore.ui.sections.remote.RemoteActivity.java

/**
 * Converts a video url to a Kodi plugin URL.
 *
 * @param playuri some URL/*from   ww  w  .ja v a2  s . c om*/
 * @return plugin URL
 */
private String toPluginUrl(Uri playuri) {
    String host = playuri.getHost();
    if (host.endsWith("svtplay.se")) {
        Pattern pattern = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.)?svtplay\\.se\\/video\\/(\\d+\\/.*)",
                Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(playuri.toString());
        if (matcher.matches()) {
            return "plugin://plugin.video.svtplay/?url=%2Fvideo%2F" + URLEncoder.encode(matcher.group(1))
                    + "&mode=video";
        }
    } else if (host.endsWith("vimeo.com")) {
        String last = playuri.getLastPathSegment();
        if (last.matches("\\d+")) {
            return "plugin://plugin.video.vimeo/play/?video_id=" + last;
        }
    } else if (host.endsWith("youtube.com")) {
        if (playuri.getPathSegments().contains("playlist")) {
            return "plugin://plugin.video.youtube/play/?order=default&playlist_id="
                    + playuri.getQueryParameter("list");
        } else {
            return "plugin://plugin.video.youtube/play/?video_id=" + playuri.getQueryParameter("v");
        }
    } else if (host.endsWith("youtu.be")) {
        return "plugin://plugin.video.youtube/play/?video_id=" + playuri.getLastPathSegment();
    }
    return null;
}

From source file:com.openerp.addons.messages.MessageComposeActivty.java

/**
 * getting real path from attachment URI.
 * /*from w ww .  j  ava2  s.  c  om*/
 * @param contentUri
 * @return
 */
private String getFilenameFromUri(Uri contentUri) {
    String filename = "unknown";
    if (contentUri.getScheme().toString().compareTo("content") == 0) {
        Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            filename = cursor.getString(column_index);
            File fl = new File(filename);
            filename = fl.getName();
        }
    } else if (contentUri.getScheme().compareTo("file") == 0) {
        filename = contentUri.getLastPathSegment().toString();
    } else {
        filename = filename + "_" + contentUri.getLastPathSegment();
    }
    return filename;
}