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:ch.luklanis.esscan.history.HistoryActivity.java

private Uri createDTAFile(long bankProfileId) {
    List<HistoryItem> historyItems = mHistoryManager.buildHistoryItemsForDTA(bankProfileId);
    BankProfile bankProfile = mHistoryManager.getBankProfile(bankProfileId);

    String error = dtaFileCreator.getFirstError(bankProfile, historyItems);

    if (!TextUtils.isEmpty(error)) {
        setOkAlert(error);//  ww w .ja  va  2s .c  o m
        return null;
    }

    CharSequence dta = dtaFileCreator.buildDTA(bankProfile, historyItems);

    if (!dtaFileCreator.saveDTAFile(dta.toString())) {
        setOkAlert(R.string.msg_unmount_usb);
        return null;
    } else {
        Uri dtaFileUri = dtaFileCreator.getDTAFileUri();
        String dtaFileName = dtaFileUri.getLastPathSegment();

        new HistoryExportUpdateAsyncTask(mHistoryManager, dtaFileName)
                .execute(historyItems.toArray(new HistoryItem[historyItems.size()]));

        this.dtaFileCreator = new DTAFileCreator(getApplicationContext());

        Toast toast = Toast.makeText(this,
                getResources().getString(R.string.msg_dta_saved, dtaFileUri.getPath()), Toast.LENGTH_LONG);
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.show();

        return dtaFileUri;
    }
}

From source file:can.yrt.onebusaway.RouteInfoListFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // We have a menu item to show in action bar.
    setHasOptionsMenu(true);/*from  w  ww.  j  av  a 2 s.  c om*/
    registerForContextMenu(getListView());

    // Start out with a progress indicator.
    setListShown(false);

    // Initialize the expandable list
    ExpandableListView list = (ExpandableListView) getListView();
    list.setOnChildClickListener(mChildClick);

    // Get the route ID from the "uri" argument
    Uri uri = (Uri) getArguments().getParcelable(FragmentUtils.URI);
    if (uri == null) {
        Log.e(TAG, "No URI in arguments");
        return;
    }
    mRouteId = uri.getLastPathSegment();

    getLoaderManager().initLoader(ROUTE_INFO_LOADER, null, mRouteCallback);
    getLoaderManager().initLoader(ROUTE_STOPS_LOADER, null, mStopsCallback);
}

From source file:com.rerum.beans.StorageActivity.java

private void uploadFromUri(Uri fileUri) {
    Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());

    // [START get_child_ref]
    // Get a reference to store file at photos/<FILENAME>.jpg
    final StorageReference photoRef = mStorageRef.child("photos").child(fileUri.getLastPathSegment());
    // [END get_child_ref]

    // Upload file to Firebase Storage
    // [START_EXCLUDE]
    showProgressDialog();/*from  w  w  w  .j a va  2s. com*/
    // [END_EXCLUDE]
    Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
    photoRef.putFile(fileUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // Upload succeeded
            Log.d(TAG, "uploadFromUri:onSuccess");

            // Get the public download URL
            mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();

            // [START_EXCLUDE]
            hideProgressDialog();
            updateUI(mAuth.getCurrentUser());
            // [END_EXCLUDE]
        }
    }).addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Upload failed
            Log.w(TAG, "uploadFromUri:onFailure", exception);

            mDownloadUrl = null;

            // [START_EXCLUDE]
            hideProgressDialog();
            Toast.makeText(StorageActivity.this, "Error: upload failed", Toast.LENGTH_SHORT).show();
            updateUI(mAuth.getCurrentUser());
            // [END_EXCLUDE]
        }
    });
}

From source file:com.eusecom.attendance.StorageActivity.java

private void uploadFromUri(Uri fileUri) {
    Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());

    // [START get_child_ref]
    // Get a reference to store file at photos/<FILENAME>.jpg
    //final StorageReference photoRef = mStorageRef.child("photos").child(fileUri.getLastPathSegment());
    final StorageReference photoRef = mStorageRef.child(fileUri.getLastPathSegment());
    // [END get_child_ref]

    // Upload file to Firebase Storage
    // [START_EXCLUDE]
    showProgressDialog();//  w  w  w .j ava2  s .  c  o  m
    // [END_EXCLUDE]
    Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
    photoRef.putFile(fileUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // Upload succeeded
            Log.d(TAG, "uploadFromUri:onSuccess");

            // Get the public download URL
            mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();

            // [START_EXCLUDE]
            hideProgressDialog();
            updateUI(mAuth.getCurrentUser());
            // [END_EXCLUDE]
        }
    }).addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Upload failed
            Log.w(TAG, "uploadFromUri:onFailure", exception);

            mDownloadUrl = null;

            // [START_EXCLUDE]
            hideProgressDialog();
            Toast.makeText(StorageActivity.this, "Error: upload failed", Toast.LENGTH_SHORT).show();
            updateUI(mAuth.getCurrentUser());
            // [END_EXCLUDE]
        }
    });
}

From source file:com.hivewallet.androidclient.wallet.AddressBookProvider.java

@Override
public Uri insert(final Uri uri, final ContentValues values) {
    if (uri.getPathSegments().size() != 1)
        throw new IllegalArgumentException(uri.toString());

    final String address = uri.getLastPathSegment();
    values.put(KEY_ADDRESS, address);/*from w  ww .  j av a 2  s  .c o  m*/

    long rowId = helper.getWritableDatabase().insertOrThrow(DATABASE_TABLE, null, values);

    final Uri rowUri = contentUri(getContext().getPackageName()).buildUpon().appendPath(address)
            .appendPath(Long.toString(rowId)).build();

    String photo = values.getAsString(KEY_PHOTO);
    if (photo != null)
        helper.setPhotoAssetAsPermanent(photo, true);

    getContext().getContentResolver().notifyChange(rowUri, null);

    return rowUri;
}

From source file:org.fdroid.fdroid.net.DownloaderService.java

/**
 * This method is invoked on the worker thread with a request to process.
 * Only one Intent is processed at a time, but the processing happens on a
 * worker thread that runs independently from other application logic.
 * So, if this code takes a long time, it will hold up other requests to
 * the same DownloaderService, but it will not hold up anything else.
 * When all requests have been handled, the DownloaderService stops itself,
 * so you should not ever call {@link #stopSelf}.
 * <p/>//from  w w w .  j  a  va2 s  . c  o m
 * Downloads are put into subdirectories based on hostname/port of each repo
 * to prevent files with the same names from conflicting.  Each repo enforces
 * unique APK file names on the server side.
 *
 * @param intent The {@link Intent} passed via {@link
 *               android.content.Context#startService(Intent)}.
 */
protected void handleIntent(Intent intent) {
    final Uri uri = intent.getData();
    File downloadDir = new File(Utils.getApkCacheDir(this), uri.getHost() + "-" + uri.getPort());
    downloadDir.mkdirs();
    final SanitizedFile localFile = new SanitizedFile(downloadDir, uri.getLastPathSegment());
    final String packageName = getPackageNameFromIntent(intent);
    sendBroadcast(uri, Downloader.ACTION_STARTED, localFile);

    if (Preferences.get().isUpdateNotificationEnabled()) {
        Notification notification = createNotification(intent.getDataString(), getPackageNameFromIntent(intent))
                .build();
        startForeground(NOTIFY_DOWNLOADING, notification);
    }

    try {
        downloader = DownloaderFactory.create(this, uri, localFile);
        downloader.setListener(new Downloader.DownloaderProgressListener() {
            @Override
            public void sendProgress(URL sourceUrl, int bytesRead, int totalBytes) {
                if (isActive(uri.toString())) {
                    Intent intent = new Intent(Downloader.ACTION_PROGRESS);
                    intent.setData(uri);
                    intent.putExtra(Downloader.EXTRA_BYTES_READ, bytesRead);
                    intent.putExtra(Downloader.EXTRA_TOTAL_BYTES, totalBytes);
                    localBroadcastManager.sendBroadcast(intent);

                    if (Preferences.get().isUpdateNotificationEnabled()) {
                        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        Notification notification = createNotification(uri.toString(), packageName)
                                .setProgress(totalBytes, bytesRead, false).build();
                        nm.notify(NOTIFY_DOWNLOADING, notification);
                    }
                }
            }
        });
        downloader.download();
        sendBroadcast(uri, Downloader.ACTION_COMPLETE, localFile);
        DownloadCompleteService.notify(this, packageName, intent.getDataString());
    } catch (InterruptedException e) {
        sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile);
    } catch (IOException e) {
        e.printStackTrace();
        sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile, e.getLocalizedMessage());
    } finally {
        if (downloader != null) {
            downloader.close();
        }
        // May have already been removed in response to a cancel intent, but that wont cause
        // problems if we ask to remove it again.
        QUEUE_WHATS.remove(uri.toString());
        stopForeground(true);
    }
    downloader = null;
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferDBBase.java

/**
 * Updates records in the table synchronously.
 *
 * @param uri A Uri of the specific record.
 * @param values The values to update./*ww w . j av a 2s .c o m*/
 * @param whereClause The "where" clause of sql.
 * @param whereArgs Strings in the "where" clause.
 * @return Number of rows updated.
 */
public synchronized int update(Uri uri, ContentValues values, String whereClause, String[] whereArgs) {
    final int uriType = uriMatcher.match(uri);
    int rowsUpdated = 0;
    ensureDatabaseOpen();
    switch (uriType) {
    case TRANSFERS:
        rowsUpdated = database.update(TransferTable.TABLE_TRANSFER, values, whereClause, whereArgs);
        break;
    case TRANSFER_ID:
        final String id = uri.getLastPathSegment();
        if (TextUtils.isEmpty(whereClause)) {
            rowsUpdated = database.update(TransferTable.TABLE_TRANSFER, values,
                    TransferTable.COLUMN_ID + "=" + id, null);
        } else {
            rowsUpdated = database.update(TransferTable.TABLE_TRANSFER, values,
                    TransferTable.COLUMN_ID + "=" + id + " and " + whereClause, whereArgs);
        }
        break;
    default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    return rowsUpdated;
}

From source file:edu.stanford.mobisocial.dungbeetle.ui.wizard.ChangePictureActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_feed_home);

    checked = new boolean[filterTypes.length];

    for (int x = 0; x < filterTypes.length; x++) {
        checked[x] = true;//from   w ww. j  a v  a  2  s .  c om
    }

    findViewById(R.id.btn_broadcast).setVisibility(View.GONE);
    mContactId = getIntent().getLongExtra("contact_id", -1);
    if (mContactId == -1) {
        Uri data = getIntent().getData();
        if (data != null) {
            try {
                mContactId = Long.parseLong(data.getLastPathSegment());
            } catch (NumberFormatException e) {
            }
        }
    }

    Bundle args = new Bundle();
    args.putLong("contact_id", mContactId);
    Fragment profileFragment = new ViewProfileFragment();
    profileFragment.setArguments(args);

    doTitleBar(this, "My Profile");
    mLabels.add("View");
    mLabels.add("Edit");
    mFragments.add(profileFragment);
    mFragments.add(new EditProfileFragment());

    Uri privateUri = Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/feeds/private");
    mLabels.add("Notes");
    Fragment feedView = new FeedViewFragment();
    args = new Bundle(args);
    args.putParcelable(FeedViewFragment.ARG_FEED_URI, privateUri);
    feedView.setArguments(args);
    //mFragments.add(feedView);

    PagerAdapter adapter = new ViewFragmentAdapter(getSupportFragmentManager(), mFragments);
    mViewPager = (ViewPager) findViewById(R.id.feed_pager);
    mViewPager.setAdapter(adapter);
    mViewPager.setOnPageChangeListener(this);

    ViewGroup group = (ViewGroup) findViewById(R.id.tab_frame);
    int i = 0;
    for (String s : mLabels) {
        Button button = new Button(this);
        button.setText(s);
        button.setTextSize(18f);

        button.setLayoutParams(CommonLayouts.FULL_HEIGHT);
        button.setTag(i++);
        button.setOnClickListener(mViewSelected);

        group.addView(button);
        mButtons.add(button);
    }

    // Listen for future changes
    Uri feedUri;
    if (mContactId == Contact.MY_ID) {
        feedUri = Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/feeds/me");
    } else {
        feedUri = Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/contacts");
    }
    mProfileContentObserver = new ProfileContentObserver(mHandler);
    getContentResolver().registerContentObserver(feedUri, true, mProfileContentObserver);

    onPageSelected(0);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Click on the avatar to take a profile picture of yourself.").setCancelable(false)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    AlertDialog alert = builder.create();
    alert.show();
}

From source file:com.jaspersoft.android.jaspermobile.activities.profile.ServerProfileActivity.java

private void persistProfileData() {
    if (profileId == 0) {
        Uri uri = getContentResolver().insert(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI,
                mServerProfile.getContentValues());
        profileId = Long.valueOf(uri.getLastPathSegment());
        Toast.makeText(this, getString(R.string.spm_profile_created_toast, alias), Toast.LENGTH_LONG).show();
    } else {/*  w  ww.jav a 2s  .  co  m*/
        String selection = ServerProfilesTable._ID + " =?";
        String[] selectionArgs = { String.valueOf(profileId) };
        getContentResolver().update(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI,
                mServerProfile.getContentValues(), selection, selectionArgs);
        Toast.makeText(this, getString(R.string.spm_profile_updated_toast, alias), Toast.LENGTH_LONG).show();
    }
    getContentResolver().notifyChange(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI, null);
}

From source file:com.ultramegasoft.flavordex2.fragment.AbsPhotosFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    final Context context = getContext();
    if (context != null && resultCode == Activity.RESULT_OK) {
        final ContentResolver cr = context.getContentResolver();
        Uri uri = null;
        switch (requestCode) {
        case REQUEST_CAPTURE_IMAGE:
            try {
                uri = mCapturedPhoto;/*from  w w  w  .  j  a  va2  s.  c o  m*/
                if (uri != null) {
                    MediaStore.Images.Media.insertImage(cr, uri.getPath(), uri.getLastPathSegment(), null);
                }
            } catch (FileNotFoundException e) {
                Log.e(TAG, "Failed to save file", e);
            }
            break;
        case REQUEST_SELECT_IMAGE:
            if (data != null) {
                uri = data.getData();
            }
            break;
        }

        if (uri != null) {
            mPhotoLoader = new PhotoLoader(context, this, uri);
            mPhotoLoader.execute();
        }
    }
}