4

Нужно выбрать фотку из галереи. Вот код, в котором при клике переходим в галерею:

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

Вот переопределение метода onActivityResult:

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);
    }

Все запускается, все хорошо, но при выборе фотки не возвращается в приложение и не ставит фотку в ImageView. Через логирование узнал, что очему то не запускается onActivityResult. Что делать ?

UPDATE

Все происходит в фрагменте. Я думал в этом и ошибка, но в методе onActivityResult в активности так же ничего не происходит.

10
  • Вот так пробовали: Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);?
    – ЮрийСПб
    24 июн 2016 в 18:31
  • к сожаление не помогает (
    – Samuliak
    24 июн 2016 в 18:33
  • А так: Intent i = new Intent(Intent.ACTION_GET_CONTENT);?
    – ЮрийСПб
    24 июн 2016 в 18:35
  • такая же проблема. Оно почему то не возвращается в приложение... Возможно потому, что все происходит во фрагментах ? Или это не имеет значение ?
    – Samuliak
    24 июн 2016 в 18:41
  • Возможно, у вас что-то не так в манифесте, в атрибуте android:launchMode у активити
    – ЮрийСПб
    24 июн 2016 в 18:48

2 ответа 2

3

Если вы вызываете startActivity из фрагмента то onActivityResult нужно ловить в фрагменте, а если из activity то в activity

Пример рабочего кода (использовал в проекте):

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

Далее 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));
                ...
}

По просьбе 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
                );
            }
        }
    }
7
  • Что значит "ImagePickUpUtil" в строке: File file = new File(ImagePickUpUtil.getRealPathFromURI(this,selectedImage));
    – Samuliak
    27 июн 2016 в 20:21
  • @Samuliak Это класс, где он умеет парсить из uri реальный путь к файлу на устройстве 27 июн 2016 в 20:24
  • У меня почему то не находит данный класс, хочет, что бы его создали. В чем может быть проблема ??
    – Samuliak
    28 июн 2016 в 11:18
  • @Samuliak данный класс нужно добавлять в проект, сейчас кину его в ответ 28 июн 2016 в 11:20
  • 1
    @Samuliak Нет, его нет в стандартных библиотеках, создайте его 28 июн 2016 в 11:32
0

Похожая проблема. Удаление строки

android:noHistory="true"

из описания activity решило проблему

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.