List of usage examples for android.net Uri getPath
@Nullable public abstract String getPath();
From source file:io.ionic.links.IonicDeeplink.java
public void handleIntent(Intent intent) { final String intentString = intent.getDataString(); // read intent String action = intent.getAction(); Uri url = intent.getData(); JSONObject bundleData = this._bundleToJson(intent.getExtras()); Log.d(TAG, "Got a new intent: " + intentString + " " + intent.getScheme() + " " + action + " " + url); // if app was not launched by the url - ignore if (!Intent.ACTION_VIEW.equals(action) || url == null) { return;/*from www . j a va2s . c o m*/ } // store message and try to consume it try { lastEvent = new JSONObject(); lastEvent.put("url", url.toString()); lastEvent.put("path", url.getPath()); lastEvent.put("queryString", url.getQuery()); lastEvent.put("scheme", url.getScheme()); lastEvent.put("host", url.getHost()); lastEvent.put("fragment", url.getFragment()); lastEvent.put("extra", bundleData); consumeEvents(); } catch (JSONException ex) { Log.e(TAG, "Unable to process URL scheme deeplink", ex); } }
From source file:com.google.android.apps.muzei.util.IOUtil.java
public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring) throws OpenUriException { if (uri == null) { throw new IllegalArgumentException("Uri cannot be empty"); }// w ww . ja va2 s . c om String scheme = uri.getScheme(); InputStream in = null; if ("content".equals(scheme)) { try { in = context.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { throw new OpenUriException(false, e); } catch (SecurityException e) { throw new OpenUriException(false, e); } } else if ("file".equals(scheme)) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) { AssetManager assetManager = context.getAssets(); StringBuilder assetPath = new StringBuilder(); for (int i = 1; i < segments.size(); i++) { if (i > 1) { assetPath.append("/"); } assetPath.append(segments.get(i)); } try { in = assetManager.open(assetPath.toString()); } catch (IOException e) { throw new OpenUriException(false, e); } } else { try { in = new FileInputStream(new File(uri.getPath())); } catch (FileNotFoundException e) { throw new OpenUriException(false, e); } } } else if ("http".equals(scheme) || "https".equals(scheme)) { OkHttpClient client = new OkHttpClient(); HttpURLConnection conn = null; int responseCode = 0; String responseMessage = null; try { conn = client.open(new URL(uri.toString())); conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); conn.setReadTimeout(DEFAULT_READ_TIMEOUT); responseCode = conn.getResponseCode(); responseMessage = conn.getResponseMessage(); if (!(responseCode >= 200 && responseCode < 300)) { throw new IOException("HTTP error response."); } if (reqContentTypeSubstring != null) { String contentType = conn.getContentType(); if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) { throw new IOException("HTTP content type '" + contentType + "' didn't match '" + reqContentTypeSubstring + "'."); } } in = conn.getInputStream(); } catch (MalformedURLException e) { throw new OpenUriException(false, e); } catch (IOException e) { if (conn != null && responseCode > 0) { throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e); } else { throw new OpenUriException(false, e); } } } return in; }
From source file:com.hsbadr.MultiSystem.MainActivity.java
@SuppressLint("NewApi") @SuppressWarnings("deprecation") @Override/* www.java2 s. co m*/ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.activity_main); /** * Before anything we need to check if the config files exist to avoid * FC is they don't * * @see #checkIfConfigExists() */ checkIfConfigExists(); /** * Now it's all good because if no configuration was found we have * copied a default one over. * * @see #checkIfConfigExists() */ setAppConfigInPrefs(); headers = getPluginTabs(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); /* * set a custom shadow that overlays the main content when the drawer * opens */ mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); /* set up the drawer's list view with items and click listener */ ArrayAdapter<String> pimpAdapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerHeaders); mDrawerList.setAdapter(pimpAdapter); Log.e("FIRST POS", mDrawerList.getFirstVisiblePosition() + ""); Log.e("LAST POS", mDrawerList.getLastVisiblePosition() + ""); View child = mDrawerList.getChildAt(mDrawerList.getFirstVisiblePosition()); if (child != null && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) child.setBackground(getColouredTouchFeedback()); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); /** Set the user-defined ActionBar icon */ File file = new File(getFilesDir() + "/.MultiSystem/icon.png"); if (file.exists()) { try { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); Uri iconUri = Uri.fromFile(new File(getFilesDir() + "/.MultiSystem/icon.png")); Bitmap icon = BitmapFactory.decodeFile(iconUri.getPath()); Drawable ic = new BitmapDrawable(icon); getSupportActionBar().setIcon(ic); } catch (NullPointerException e) { Log.e("NPE", e.getMessage()); } } /* * ActionBarDrawerToggle ties together the proper interactions between * the sliding drawer and the action bar app icon */ mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.app_name, /* "open drawer" description for accessibility */ R.string.app_name /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { invalidateOptionsMenu(); /* * creates call to * onPrepareOptionsMenu() */ } public void onDrawerOpened(View drawerView) { invalidateOptionsMenu(); /* * creates call to * onPrepareOptionsMenu() */ } }; mDrawerLayout.setDrawerListener(mDrawerToggle); /** Tabs adapter using the PagerSlidingStrip library */ tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs); pager = (ViewPager) findViewById(R.id.pager); MyPagerAdapter adapter = new MyPagerAdapter(this.getSupportFragmentManager()); pager.setAdapter(adapter); pager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics()); pager.setPageMargin(pageMargin); tabs.setViewPager(pager); tabs.setOnPageChangeListener(this); changeColor(Color.parseColor(getPluginColor())); pager.setOffscreenPageLimit(5); }
From source file:com.android.messaging.mmslib.pdu.PduPersister.java
/** * This method expects uri in the following format * content://media/<table_name>/<row_index> (or) * file://sdcard/test.mp4//from w w w . j a v a 2s . c o m * http://test.com/test.mp4 * * Here <table_name> shall be "video" or "audio" or "images" * <row_index> the index of the content in given table */ public static String convertUriToPath(final Context context, final Uri uri) { String path = null; if (null != uri) { final String scheme = uri.getScheme(); if (null == scheme || scheme.equals("") || scheme.equals(ContentResolver.SCHEME_FILE)) { path = uri.getPath(); } else if (scheme.equals("http")) { path = uri.toString(); } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) { final String[] projection = new String[] { MediaStore.MediaColumns.DATA }; Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, null, null, null); if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) { throw new IllegalArgumentException("Given Uri could not be found" + " in media store"); } final int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); path = cursor.getString(pathIndex); } catch (final SQLiteException e) { throw new IllegalArgumentException( "Given Uri is not formatted in a way " + "so that it can be found in media store."); } finally { if (null != cursor) { cursor.close(); } } } else { throw new IllegalArgumentException("Given Uri scheme is not supported"); } } return path; }
From source file:mobisocial.musubi.util.UriImage.java
public UriImage(Context context, Uri uri) { if ((null == context) || (null == uri)) { throw new IllegalArgumentException(); }//w ww . j a va 2s . co m mRotation = PhotoTaker.rotationForImage(context, uri); String scheme = uri.getScheme(); if (scheme.equals("content")) { try { initFromContentUri(context, uri); } catch (Exception e) { Log.w(TAG, "last-ditch image params"); mPath = uri.getPath(); mContentType = context.getContentResolver().getType(uri); } } else if (uri.getScheme().equals("file")) { initFromFile(context, uri); } else { mPath = uri.getPath(); } mSrc = mPath.substring(mPath.lastIndexOf('/') + 1); if (mSrc.startsWith(".") && mSrc.length() > 1) { mSrc = mSrc.substring(1); } // Some MMSCs appear to have problems with filenames // containing a space. So just replace them with // underscores in the name, which is typically not // visible to the user anyway. mSrc = mSrc.replace(' ', '_'); mContext = context; mUri = uri; }
From source file:bmcx.aiton.com.passenger.view.activity.UploadUserDataActivity.java
/** * /*from w w w. j a v a 2s. c o m*/ * * @param uploadFile */ public void postFile(Uri uploadFile, String forUpLoadUrl) { //?? mProgressDialog = android.app.ProgressDialog.show(UploadUserDataActivity.this, null, "", true, true); mProgressDialog.show(); String path = uploadFile.getPath(); File file = new File(path); if (file.exists() && file.length() > 0) { RequestParams params = new RequestParams(); params.put("account_id", mUserId); try { params.put("data", file); } catch (FileNotFoundException e) { e.printStackTrace(); } AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); asyncHttpClient.post(forUpLoadUrl, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { mProgressDialog.dismiss(); //?SP? switch (mUpLoadWhatImg) { case 0: LoginState.getInstance(UploadUserDataActivity.this) .setLoginInfoSfzZm(new String(responseBody)); mIv_btn_sjzzm_updata.setImageResource(R.mipmap.xiugai_2x); mIsUploadSfzZm = true; break; case 1: LoginState.getInstance(UploadUserDataActivity.this) .setLoginInfoSfzFm(new String(responseBody)); mIv_btn_sjzfm_updata.setImageResource(R.mipmap.xiugai_2x); mIsUploadSfzFm = true; break; case 2: LoginState.getInstance(UploadUserDataActivity.this) .setLoginInfoJszZm(new String(responseBody)); mIv_btn_jszzm_updata.setImageResource(R.mipmap.xiugai_2x); mIsUploadJszZm = true; break; case 3: LoginState.getInstance(UploadUserDataActivity.this) .setLoginInfoJszFm(new String(responseBody)); mIv_btn_jszfm_updata.setImageResource(R.mipmap.xiugai_2x); mIsUploadJszFm = true; break; } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); } else { Toast.makeText(UploadUserDataActivity.this, "?", Toast.LENGTH_LONG) .show(); switch (mUpLoadWhatImg) { case 0: mIv_sfzzm.setImageResource(R.mipmap.shenfzzhengmian_2x); break; case 1: mIv_sfzfm.setImageResource(R.mipmap.shenfzfanmian_2x); break; case 2: mIv_jszzm.setImageResource(R.mipmap.jiashizzhengmian_2x); break; case 3: mIv_jszfm.setImageResource(R.mipmap.jiashizfanmian_2x); break; } } }
From source file:com.ximai.savingsmore.save.activity.FourStepRegisterActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode != RESULT_OK) { return;/*from w ww.j a v a 2 s . co m*/ } else if (requestCode == PICK_FROM_CAMERA || requestCode == PICK_FROM_IMAGE) { Uri uri = null; if (null != intent && intent.getData() != null) { uri = intent.getData(); } else { String fileName = PreferencesUtils.getString(this, "tempName"); uri = Uri.fromFile(new File(FileSystem.getCachesDir(this, true).getAbsolutePath(), fileName)); } if (uri != null) { cropImage(uri, CROP_PHOTO_CODE); } } else if (requestCode == CROP_PHOTO_CODE) { Uri photoUri = intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT); if (isslinece) { MyImageLoader.displayDefaultImage("file://" + photoUri.getPath(), slience_image); zhizhao_path = photoUri.toString(); try { upLoadImage(new File((new URI(photoUri.toString()))), "BusinessLicense"); } catch (URISyntaxException e) { e.printStackTrace(); } } else if (isZhengshu) { MyImageLoader.displayDefaultImage("file://" + photoUri.getPath(), zhengshu_iamge); xukezheng_path = photoUri.toString(); try { upLoadImage(new File((new URI(photoUri.toString()))), "LicenseKey"); } catch (URISyntaxException e) { e.printStackTrace(); } //upLoadImage(new File((new URI(photoUri.toString()))), "Photo"); } else if (isItem) { if (images.size() < 10) { shangpu_path.add(photoUri.toString()); try { upLoadImage(new File((new URI(photoUri.toString()))), "Seller"); } catch (URISyntaxException e) { e.printStackTrace(); } } else { Toast.makeText(FourStepRegisterActivity.this, "?9", Toast.LENGTH_SHORT).show(); } } //addImage(imagePath); } }
From source file:ch.uzh.supersede.feedbacklibrary.AnnotateImageActivity.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { Uri croppedImageUri = result.getUri(); File croppedImageFile = new File(croppedImageUri.getPath()); annotateImageView.updateCroppedImageHistory(croppedImageFile); } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Toast toast = Toast.makeText(getApplicationContext(), R.string.supersede_feedbacklibrary_error_text, Toast.LENGTH_SHORT); toast.show();// w w w. j a v a 2 s .c om } } }
From source file:com.keepassdroid.fileselect.FileSelectActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); fileHistory = App.getFileHistory();//from ww w .ja va 2 s. c o m if (fileHistory.hasRecentFiles()) { recentMode = true; setContentView(R.layout.file_selection); } else { setContentView(R.layout.file_selection_no_recent); } mList = (ListView) findViewById(R.id.file_list); mList.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { onListItemClick((ListView) parent, v, position, id); } }); // Open button Button openButton = (Button) findViewById(R.id.open); openButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String fileName = Util.getEditText(FileSelectActivity.this, R.id.file_filename); try { PasswordActivity.Launch(FileSelectActivity.this, fileName); } catch (ContentFileNotFoundException e) { Toast.makeText(FileSelectActivity.this, R.string.file_not_found_content, Toast.LENGTH_LONG) .show(); } catch (FileNotFoundException e) { Toast.makeText(FileSelectActivity.this, R.string.FileNotFound, Toast.LENGTH_LONG).show(); } } }); // Create button Button createButton = (Button) findViewById(R.id.create); createButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String filename = Util.getEditText(FileSelectActivity.this, R.id.file_filename); // Make sure file name exists if (filename.length() == 0) { Toast.makeText(FileSelectActivity.this, R.string.error_filename_required, Toast.LENGTH_LONG) .show(); return; } // Try to create the file File file = new File(filename); try { if (file.exists()) { Toast.makeText(FileSelectActivity.this, R.string.error_database_exists, Toast.LENGTH_LONG) .show(); return; } File parent = file.getParentFile(); if (parent == null || (parent.exists() && !parent.isDirectory())) { Toast.makeText(FileSelectActivity.this, R.string.error_invalid_path, Toast.LENGTH_LONG) .show(); return; } if (!parent.exists()) { // Create parent dircetory if (!parent.mkdirs()) { Toast.makeText(FileSelectActivity.this, R.string.error_could_not_create_parent, Toast.LENGTH_LONG).show(); return; } } file.createNewFile(); } catch (IOException e) { Toast.makeText(FileSelectActivity.this, getText(R.string.error_file_not_create) + " " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show(); return; } // Prep an object to collect a password once the database has // been created CollectPassword password = new CollectPassword(new LaunchGroupActivity(filename)); // Create the new database CreateDB create = new CreateDB(FileSelectActivity.this, filename, password, true); ProgressTask createTask = new ProgressTask(FileSelectActivity.this, create, R.string.progress_create); createTask.run(); } }); ImageButton browseButton = (ImageButton) findViewById(R.id.browse_button); browseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (StorageAF.useStorageFramework(FileSelectActivity.this)) { Intent i = new Intent(StorageAF.ACTION_OPEN_DOCUMENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); startActivityForResult(i, OPEN_DOC); } else { Intent i; i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); try { startActivityForResult(i, GET_CONTENT); } catch (ActivityNotFoundException e) { lookForOpenIntentsFilePicker(); } catch (SecurityException e) { lookForOpenIntentsFilePicker(); } } } private void lookForOpenIntentsFilePicker() { if (Interaction.isIntentAvailable(FileSelectActivity.this, Intents.OPEN_INTENTS_FILE_BROWSE)) { Intent i = new Intent(Intents.OPEN_INTENTS_FILE_BROWSE); i.setData(Uri.parse("file://" + Util.getEditText(FileSelectActivity.this, R.id.file_filename))); try { startActivityForResult(i, FILE_BROWSE); } catch (ActivityNotFoundException e) { showBrowserDialog(); } } else { showBrowserDialog(); } } private void showBrowserDialog() { BrowserDialog diag = new BrowserDialog(FileSelectActivity.this); diag.show(); } }); fillData(); registerForContextMenu(mList); // Load default database SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String fileName = prefs.getString(PasswordActivity.KEY_DEFAULT_FILENAME, ""); if (fileName.length() > 0) { Uri dbUri = UriUtil.parseDefaultFile(fileName); String scheme = dbUri.getScheme(); if (!EmptyUtils.isNullOrEmpty(scheme) && scheme.equalsIgnoreCase("file")) { String path = dbUri.getPath(); File db = new File(path); if (db.exists()) { try { PasswordActivity.Launch(FileSelectActivity.this, path); } catch (Exception e) { // Ignore exception } } } else { try { PasswordActivity.Launch(FileSelectActivity.this, dbUri.toString()); } catch (Exception e) { // Ignore exception } } } }
From source file:com.rks.musicx.ui.activities.MainActivity.java
/** * play song from outside of the app//from www . j av a2 s .c om * @param data */ private void openFile(Uri data) { List<Song> playList = Helper.getSongMetaData(MainActivity.this, data.getPath()); if (playList.size() > 0) { onSongSelected(playList, 0); } }