Java Code Examples for android.content.Intent.getData()

The following are Jave code examples for showing how to use getData() of the android.content.Intent class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: AyyMate-Android-RealtimeChat   File: PersonalChat.java   View Source Code Vote up 8 votes
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == RC_SIGN_IN){
        if (resultCode == RESULT_OK){
            Toast.makeText(this, "Sign in successful", Toast.LENGTH_SHORT).show();
        } else if (requestCode == RESULT_CANCELED){
            Toast.makeText(this, "Sign in cancelled", Toast.LENGTH_SHORT).show();
            finish();
        }
    } else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){
        Uri selectedImageUri = data.getData();
        StorageReference photoRef = mChatPhotoStorageReference.child(selectedImageUri.getLastPathSegment());
        photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadUrl = taskSnapshot.getDownloadUrl();
                FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
                mMessagesDatabaseReference.push().setValue(friendlyMessage);
            }
        });
    }
}
 
Example 2
Project: aos-Video   File: ListingActivity.java   View Source Code Vote up 6 votes
@Override
public void onActivityResult(int requestCode, int result, Intent data){
    super.onActivityResult(requestCode, result, data);

    if(requestCode==REQUEST_INFO_ACTIVITY&&result== RESULT_FILE_DELETED){
        Uri file = data.getData();

        for(int i = 0; i<= getFragmentManager().getBackStackEntryCount(); i++){
            Fragment frag = getFragmentManager().findFragmentByTag("fragment_"+i);//tag specified in fragmenttransaction
            if(frag != null&&frag instanceof ListingFragment){ //send uri to refresh
                ((ListingFragment)frag).onFileDelete(file);
            }
        }


    }
}
 
Example 3
Project: GitHub   File: PubkeyListActivity.java   View Source Code Vote up 6 votes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
	super.onActivityResult(requestCode, resultCode, resultData);

	switch (requestCode) {
	case REQUEST_CODE_PICK_FILE:
		if (resultCode == RESULT_OK && resultData != null) {
			Uri uri = resultData.getData();
			try {
				if (uri != null) {
					readKeyFromFile(uri);
				} else {
					String filename = resultData.getDataString();
					if (filename != null) {
						readKeyFromFile(Uri.parse(filename));
					}
				}
			} catch (IllegalArgumentException e) {
				Log.e(TAG, "Couldn't read from picked file", e);
			}
		}
		break;
	}
}
 
Example 4
Project: q-mail   File: StorageGoneReceiver.java   View Source Code Vote up 6 votes
@Override
public void onReceive(final Context context, final Intent intent) {
    final String action = intent.getAction();
    final Uri uri = intent.getData();

    if (uri == null || uri.getPath() == null) {
        return;
    }

    Timber.v("StorageGoneReceiver: %s", intent);

    final String path = uri.getPath();

    if (Intent.ACTION_MEDIA_EJECT.equals(action)) {
        StorageManager.getInstance(context).onBeforeUnmount(path);
    } else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) {
        StorageManager.getInstance(context).onAfterUnmount(path);
    }
}
 
Example 5
Project: SuperNote   File: EditNotePresenter.java   View Source Code Vote up 6 votes
@TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(mView.getActivity(), uri)) {
//            如果是documentlent类型的URI,则通过docment id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePatch(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePatch(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
//            如果是content类型的uri的话,则使用普通方式处理
            imagePath = getImagePatch(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
//            若果是file类型的uri,则直接获取图片路径
            imagePath = uri.getPath();
        }
        copyFileInOtherThread(imagePath);
    }
 
Example 6
Project: CollegeDoc   File: PdfView.java   View Source Code Vote up 6 votes
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //PDF
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PDF) {

            Uri selectedUri_PDF = data.getData();
            InputStream inputstream;
            try {
                inputstream = getContentResolver().openInputStream(selectedUri_PDF);
                pdfview.fromStream(inputstream).load();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(PdfView.this, "unable to open", Toast.LENGTH_SHORT).show();
            }
        }
    }
    else
    {
        startActivity(new Intent(PdfView.this,Subjects.class));
        finish();
    }
}
 
Example 7
Project: GCSApp   File: ProjectCreateActivity.java   View Source Code Vote up 5 votes
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACacheKey.INPUT_CODE && resultCode == ACacheKey.INPUT_CODE) {
            Bundle bundle = data.getExtras();
            String resultString = bundle.getString(ACacheKey.INPUT_STRING);
            if (StringUtils.isNotEmpty(resultString) && null != inPutView) {
                inPutView.setText(resultString);
                inPutView = null;
            }
        } else if (requestCode == 998 && resultCode == 998) {
            ArrayList<String> strs = (ArrayList<String>) data.getExtras().get("data");
            mvpPresenter.upLoadPhotos(strs);
//            mvpPresenter.uploadPhoto(BitmapUtil.saveBitmapFile(BitmapUtil.getBitmap(strs), pathurl), type);
        } else if (resultCode == RESULT_OK) {
            String pathUrl;
            if (requestCode == 1) {
                pathUrl = mPhotoPath;
            } else {
                Uri uri = data.getData();
                if (!TextUtils.isEmpty(uri.getAuthority())) {
                    pathUrl = getPathFromUri(uri);
                } else {
                    pathUrl = uri.getPath();
                }
            }
            mvpPresenter.uploadPhoto(BitmapUtil.saveBitmapFile(BitmapUtil.getBitmap(pathUrl), pathUrl), type);
        }
    }
 
Example 8
Project: AndroidPdfViewerV2   File: PDFViewActivity.java   View Source Code Vote up 5 votes
@OnActivityResult(REQUEST_CODE)
public void onResult(int resultCode, Intent intent) {
    if (resultCode == RESULT_OK) {
        uri = intent.getData();
        displayFromUri(uri);
    }
}
 
Example 9
Project: Goalie_Android   File: ProfileFragment.java   View Source Code Vote up 5 votes
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == Constants.RESULT_PROFILE_IMAGE_SELECTED) { // image selected. Crop the image
        if (resultCode == RESULT_OK && data != null && data.getData() != null) {
            startImageCrop(data.getData());
        } else if (resultCode != RESULT_CANCELED) {
            Toast.makeText(getActivity(), getString(R.string.image_selection_error), Toast.LENGTH_SHORT).show();
        }
    } else if (requestCode == Constants.RESULT_PROFILE_IMAGE_TAKEN) { // image taken. Crop the image
        if (resultCode == RESULT_OK) {
            Uri uri = FileProvider.getUriForFile(getActivity(), getString(R.string.file_provider),
                    mPresenter.getTempImageFileForOwner());
            getActivity().revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            startImageCrop(uri);
        } else if (resultCode != RESULT_CANCELED) {
            Toast.makeText(getActivity(), getString(R.string.image_taking_error), Toast.LENGTH_SHORT).show();
        }
    } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { // image cropped
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Bitmap bitmap = ImageHelper.decodeSampledBitmapFromUri(getActivity().getContentResolver(),
                    result.getUri(), Constants.PROFILE_IMAGE_WIDTH, Constants.PROFILE_IMAGE_HEIGHT);
            mPresenter.newProfileImageSelected(bitmap);
        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Diagnostic.logError(Diagnostic.DiagnosticFlag.Other, "Image failed to be cropped");
            Toast.makeText(getActivity(), getString(R.string.image_selection_error), Toast.LENGTH_SHORT).show();
        }
    } else if (requestCode == Constants.RESULT_PROFILE_UPDATE && resultCode == Activity.RESULT_OK) { // bio updated
        if (getView() != null) {
            ((TextView) getView().findViewById(R.id.profile_bio)).setText(data.getStringExtra("bio"));
            Toast.makeText(getActivity(), getString(R.string.updated), Toast.LENGTH_SHORT).show();
        }
    }
}
 
Example 10
Project: MetadataEditor   File: SAFUtil.java   View Source Code Vote up 5 votes
/**
 * call this method from the activity's onResult which was passed to requestSAFPermission method
 *
 * @param activity                         the activity whose onResult has been called on returning from document picker activity
 * @param customKeyForStoringPermissionKey a custom key for storing saf permission uri
 * @throws SAFOperationFailedException if the user did not gave the permission
 */
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data, @Nullable String customKeyForStoringPermissionKey) throws SAFOperationFailedException {
    if (requestCode == REQUEST_CODE_SAF && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
        String p = sharedPreferences.getString(getKeyForStoringPermissionKey(customKeyForStoringPermissionKey), null);
        Uri oldUri = null;
        if (p != null) oldUri = Uri.parse(p);
        Uri treeUri = null;
        if (resultCode == Activity.RESULT_OK) {
            treeUri = data.getData();
            if (treeUri != null)
                sharedPreferences.edit().putString(getKeyForStoringPermissionKey(customKeyForStoringPermissionKey), treeUri.toString()).commit();
            if (!TextUtils.isEmpty(customKeyForStoringPermissionKey))
                sharedPreferences.edit().putString(KEY_CUSTOM_KEY, customKeyForStoringPermissionKey).commit();
        }
        // If not confirmed SAF, or if still not writable, then revert settings.
        if (resultCode != Activity.RESULT_OK) {
            if (treeUri != null)
                sharedPreferences.edit().putString(getKeyForStoringPermissionKey(customKeyForStoringPermissionKey), oldUri.toString()).commit();
            throw new SAFOperationFailedException("responseCode of result for saf request is not RESULT_OK. Its value is " + String.valueOf(resultCode));
        }
        activity.getContentResolver().takePersistableUriPermission(treeUri, data.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
        if (runPostSAFComplete != null)
            runPostSAFComplete.run();
    }
}
 
Example 11
Project: Daedalus   File: RuleConfigFragment.java   View Source Code Vote up 5 votes
@Override
@TargetApi(Build.VERSION_CODES.KITKAT)
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        if (resultData != null) {
            Uri uri = resultData.getData();
            try {
                getActivity().getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

                String file = System.currentTimeMillis() + ".dr";//Daedalus Rule
                InputStream inputStream = getActivity().getContentResolver().openInputStream(uri);
                OutputStream outputStream = new FileOutputStream(Daedalus.rulePath + file);
                byte[] b = new byte[1024];
                while ((inputStream.read(b)) != -1) {
                    outputStream.write(b);
                }
                inputStream.close();
                outputStream.close();

                ((EditTextPreference) findPreference("ruleFilename")).setText(file);
                findPreference("ruleFilename").setSummary(file);
                ((EditTextPreference) findPreference("ruleDownloadUrl")).setText(uri.toString());
                findPreference("ruleDownloadUrl").setSummary(uri.toString());

                Snackbar.make(getView(), R.string.notice_importing_rule, Snackbar.LENGTH_LONG).show();
            } catch (Exception e) {
                Logger.logException(e);
            }
        }
    }
}
 
Example 12
Project: changApp   File: AddChanga.java   View Source Code Vote up 5 votes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        mbuttonLoadImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
}
 
Example 13
Project: NavRouter   File: TestMultiParamActivity.java   View Source Code Vote up 5 votes
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ATTENTION: This was auto-generated to handle app links.
    Intent appLinkIntent = getIntent();
    String appLinkAction = appLinkIntent.getAction();
    Uri appLinkData = appLinkIntent.getData();

    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    setContentView(linearLayout);

    TextView textView = new TextView(this);
    textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
    linearLayout.addView(textView);

    int year = ParamUtils.getIntExtra(appLinkData, "year", 0);
    double amount = ParamUtils.getDoubleExtra(appLinkData, "amount", 0.0);
    String name = ParamUtils.getStringExtra(appLinkData, "name");

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("The param is : year -> " + String.valueOf(year) + "\n");
    stringBuilder.append("The param is : amount -> " + String.valueOf(amount) + "\n");
    stringBuilder.append("The param is : name -> " + name + "\n");

    textView.setText(stringBuilder);
}
 
Example 14
Project: IFWManager   File: StringFilter.java   View Source Code Vote up 5 votes
@Override
public String getValue(ComponentName resolvedComponent, Intent intent,
                       String resolvedType) {
    Uri data = intent.getData();
    if (data != null) {
        return data.getScheme();
    }
    return null;
}
 
Example 15
Project: Android-Uri-demo   File: SettingsFragment.java   View Source Code Vote up 5 votes
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "]");
    if (data != null && data.getData() != null) {
        Log.d(TAG, "data = [" + data.getData().toString() + "]");
        Response response = new Response(data.getData());
        makeText(getContext(), response.getReason(), LENGTH_SHORT).show();
        if (response.getResponseCode() == 0) {
            sharedPreferencesManager.setStoneCode(stoneCode);
        }
    } else { makeText(getContext(), "no data content", LENGTH_SHORT).show();}
}
 
Example 16
Project: OpenHub   File: LoginPresenter.java   View Source Code Vote up 5 votes
@Override
public void handleOauth(Intent intent) {
    Uri uri = intent.getData();
    if (uri != null) {
        String code = uri.getQueryParameter("code");
        String state = uri.getQueryParameter("state");
        getToken(code, state);
    }
}
 
Example 17
Project: AndroidProgramming3e   File: CrimeFragment.java   View Source Code Vote up 4 votes
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
        return;
    }

    if (requestCode == REQUEST_DATE) {
        Date date = (Date) data
                .getSerializableExtra(DatePickerFragment.EXTRA_DATE);
        mCrime.setDate(date);
        updateCrime();
        updateDate();
    } else if (requestCode == REQUEST_CONTACT && data != null) {
        Uri contactUri = data.getData();
        // Specify which fields you want your query to return
        // values for.
        String[] queryFields = new String[]{
                ContactsContract.Contacts.DISPLAY_NAME
        };
        // Perform your query - the contactUri is like a "where"
        // clause here
        Cursor c = getActivity().getContentResolver()
                .query(contactUri, queryFields, null, null, null);
        try {
            // Double-check that you actually got results
            if (c.getCount() == 0) {
                return;
            }
            // Pull out the first column of the first row of data -
            // that is your suspect's name.
            c.moveToFirst();
            String suspect = c.getString(0);
            mCrime.setSuspect(suspect);
            updateCrime();
            mSuspectButton.setText(suspect);
        } finally {
            c.close();
        }
    } else if (requestCode == REQUEST_PHOTO) {
        Uri uri = FileProvider.getUriForFile(getActivity(),
                "com.bignerdranch.android.criminalintent.fileprovider",
                mPhotoFile);

        getActivity().revokeUriPermission(uri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        updateCrime();
        updatePhotoView();
    }
}
 
Example 18
Project: DaiGo   File: VerificationActivity.java   View Source Code Vote up 4 votes
private String handleImageBeforeKitKat(Intent data) {
    Uri uri = data.getData();
    return getImagePath(uri, null);
}
 
Example 19
Project: appinventor-extensions   File: ContactPicker.java   View Source Code Vote up 4 votes
/**
 * Callback method to get the result returned by the contact picker activity
 *
 * @param requestCode a code identifying the request.
 * @param resultCode a code specifying success or failure of the activity
 * @param data the returned data, in this case an Intent whose data field
 *        contains the contact's content provider Uri.
 */
@Override
public void resultReturned(int requestCode, int resultCode, Intent data) {
  if (requestCode == this.requestCode && resultCode == Activity.RESULT_OK) {
    Log.i("ContactPicker", "received intent is " + data);
    Uri receivedContactUri = data.getData();

    // Pre- and post-Honeycomb need different URIs.
    String desiredContactUri = "";
    if (SdkLevel.getLevel() >= SdkLevel.LEVEL_HONEYCOMB_MR1) {
      desiredContactUri = "//com.android.contacts/contact";
    } else {
      desiredContactUri = "//contacts/people";
    }

    if (checkContactUri(receivedContactUri, desiredContactUri)) {
      Cursor contactCursor = null;
      Cursor dataCursor = null;
      try {
        if (SdkLevel.getLevel() >= SdkLevel.LEVEL_HONEYCOMB_MR1) {
          CONTACT_PROJECTION = HoneycombMR1Util.getContactProjection();
          contactCursor = activityContext.getContentResolver().query(receivedContactUri,
              CONTACT_PROJECTION, null, null, null);

          String id = postHoneycombGetContactNameAndPicture(contactCursor);

          DATA_PROJECTION = HoneycombMR1Util.getDataProjection();
          dataCursor = HoneycombMR1Util.getDataCursor(id, activityContext, DATA_PROJECTION);
          postHoneycombGetContactEmailAndPhone(dataCursor);

          //explicit set TextContactUri
          contactUri = receivedContactUri.toString();
        } else {
          contactCursor = activityContext.getContentResolver().query(receivedContactUri,
              PROJECTION, null, null, null);
          preHoneycombGetContactInfo(contactCursor, receivedContactUri);
        }
        Log.i("ContactPicker",
              "Contact name = " + contactName + ", email address = " + emailAddress + ",contact Uri = " + contactUri +
              ", phone number = " + phoneNumber + ", contactPhotoUri = " +  contactPictureUri);
      } catch (Exception e) {
        // There was an exception in trying to extract the cursor from the activity context.
        // It's bad form to catch an arbitrary exception, but if there is an error here
        // it's unclear what's going on.
        Log.i("ContactPicker", "checkContactUri failed: D");
        puntContactSelection(ErrorMessages.ERROR_PHONE_UNSUPPORTED_CONTACT_PICKER);
      } finally {
        if (contactCursor != null) {
          contactCursor.close();
        }
        if (dataCursor != null) {
          dataCursor.close();
        }
      }
    } // ends if (checkContactUri ...
    AfterPicking();
  } // ends if (requestCode ...
}
 
Example 20
Project: Treebolic   File: MainActivity.java   View Source Code Vote up 4 votes
@Override
protected void onActivityResult(final int requestCode, final int resultCode, @NonNull final Intent returnIntent)
{
	// handle selection of input by other activity which returns selected input
	switch (requestCode)
	{
		case REQUEST_FILE_CODE:
		case REQUEST_BUNDLE_CODE:
		case REQUEST_SERIALIZED_CODE:
			if (resultCode == AppCompatActivity.RESULT_OK)
			{
				final Uri fileUri = returnIntent.getData();
				if (fileUri == null)
				{
					break;
				}

				Toast.makeText(this, fileUri.toString(), Toast.LENGTH_SHORT).show();
				switch (requestCode)
				{
					case REQUEST_FILE_CODE:
						setFolder(fileUri);
						tryStartTreebolic(fileUri);
						break;
					case REQUEST_BUNDLE_CODE:
						setFolder(fileUri);
						tryStartTreebolicBundle(fileUri);
						break;
					case REQUEST_SERIALIZED_CODE:
						setFolder(fileUri);
						tryStartTreebolicSerialized(fileUri);
						break;
					default:
						break;
				}
			}
			break;
		case REQUEST_DOWNLOAD_CODE:
			break;
		default:
			break;
	}
	super.onActivityResult(requestCode, resultCode, returnIntent);
}