You need to select a photo from the gallery. Here is the code in which when clicking we go to the gallery:

Intent i = new Intent(Intent.ACTION_PICK); i.setType("image/*"); startActivityForResult(i, Constants.REQUEST); 

Here is the override of the onActivityResult method:

 public void onActivityResult(int requestCode, int resultCode, Intent data) { Bitmap img = null; if (requestCode == Constants.REQUEST) { Uri selectedImage = data.getData(); try { img = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), selectedImage); } catch (IOException e) { e.printStackTrace(); } circleImageView.setImageBitmap(img); } super.onActivityResult(requestCode, resultCode, data); } 

Everything starts, everything is fine, but when choosing a photo, it does not return to the application and does not put a photo in the ImageView. Through logging I learned that onActivityResult does not run. What to do ?

UPDATE

Everything happens in the fragment. I thought this was a mistake, but nothing happens in the onActivityResult method of activity either.

  • So we tried: Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); ? - Yuriy SPb
  • unfortunately it does not help ( - Samuliak
  • And so: Intent i = new Intent(Intent.ACTION_GET_CONTENT); ? - Yuriy SPb
  • same problem. For some reason, it does not return to the application ... Perhaps because everything happens in fragments? Or does it not matter? - Samuliak
  • Perhaps you have something wrong in the manifest, in the android: launchMode attribute of the activation - YuriiSPb

1 answer 1

If you call startActivity from the fragment, then onActivityResult needs to be caught in the fragment, and if from activity then into activity

Example of working code (used in the project):

  Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_PICK); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_AVATAR); 

Next onActivityResult:

  if(requestCode == PICK_IMAGE_AVATAR && data!=null){ Uri selectedImage = data.getData(); // create file Cursor c = getContentResolver().query(selectedImage,null,null,null,null); c.moveToFirst(); String path = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA)); File file = new File(ImagePickUpUtil.getRealPathFromURI(this,selectedImage)); ... } 

At the request of ImagePickUpUtil:

 public class ImagePickUpUtil { public static final int PICK_CODE = 100; /** * Detect the available intent and open a new dialog. * * @param context */ public static void openMediaSelector(Activity context) { Intent camIntent = new Intent("android.media.action.IMAGE_CAPTURE"); Intent gallIntent = new Intent(Intent.ACTION_PICK); gallIntent.setType("image/*"); // look for available intents List<ResolveInfo> info = new ArrayList<ResolveInfo>(); List<Intent> yourIntentsList = new ArrayList<Intent>(); PackageManager packageManager = context.getPackageManager(); List<ResolveInfo> listCam = packageManager.queryIntentActivities(camIntent, 0); for (ResolveInfo res : listCam) { final Intent finalIntent = new Intent(camIntent); finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); yourIntentsList.add(finalIntent); info.add(res); } List<ResolveInfo> listGall = packageManager.queryIntentActivities(gallIntent, 0); for (ResolveInfo res : listGall) { final Intent finalIntent = new Intent(gallIntent); finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); yourIntentsList.add(finalIntent); info.add(res); } // show available intents openDialog(context, yourIntentsList, info); } /** * Open a new dialog with the detected items. * * @param context * @param intents * @param activitiesInfo */ private static void openDialog(final Activity context, final List<Intent> intents, List<ResolveInfo> activitiesInfo) { AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle("Выберите действие"); dialog.setAdapter(buildAdapter(context, activitiesInfo), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Intent intent = intents.get(id); context.startActivityForResult(intent, PICK_CODE); } }); dialog.setNeutralButton("Отмена", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.show(); } /** * Build the list of items to show using the intent_listview_row layout. * * @param context * @param activitiesInfo * @return */ private static ArrayAdapter<ResolveInfo> buildAdapter(final Context context, final List<ResolveInfo> activitiesInfo) { return new ArrayAdapter<ResolveInfo>(context, R.layout.intent_listview_row, R.id.title, activitiesInfo) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); ResolveInfo res = activitiesInfo.get(position); ImageView image = (ImageView) view.findViewById(R.id.icon); image.setImageDrawable(res.loadIcon(context.getPackageManager())); TextView textview = (TextView) view.findViewById(R.id.title); textview.setText(res.loadLabel(context.getPackageManager()).toString()); return view; } }; } // ============================================================= /** * Get absolute path of the file from it's uri * * @param context Context from your activity. * @param contentURI Uri of the file. * @return absolute path of the file */ public static String getRealPathFromURI(Context context, Uri contentURI) { String result = null; Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null); if (cursor == null) { // Source is Dropbox or other similar local file path result = contentURI.getPath(); } else { cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if(idx >= 0) { result = cursor.getString(idx); } cursor.close(); } return result; } public static Bitmap scaleImageFile(File f) { try { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // The new size we want to scale to final int REQUIRED_SIZE = 300; // Find the correct scale value. It should be the power of 2. int scale = 1; while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) { scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } // Storage Permissions private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; /** * Checks if the app has permission to write to device storage * * If the app does not has permission then the user will be prompted to grant permissions * * @param activity */ public static void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } } } 
  • What does "ImagePickUpUtil" in the line mean: File file = new File (ImagePickUpUtil.getRealPathFromURI (this, selectedImage)); - Samuliak
  • @Samuliak This is a class where he can parse from uri the real path to the file on the device - Evgeny Suetin
  • For some reason, I don’t find this class, I want to create it. What could be the problem ?? - Samuliak
  • @Samuliak this class needs to be added to the project, now I'll throw it back - Yevgeny Suetin
  • one
    @Samuliak No, it is not in the standard libraries, create it - Evgeny Suetin