0

Buenas, tengo el siguiente código y quisiera saber si se puede modificar para ser ejecutado desde un fragment, el asunto es que hay partes que no se como modificar y que se me ponen en rojo en el android studio

Este es el codigo:

private void captureImageInitialization() {
    /**
     * a selector dialog to display two image source options, from camera
     * ‘Take from camera’ and from existing files ‘Select from gallery’
     */
    final String[] items = new String[] { "Tomar desde la cámara",
            "Seleccionar de la galeria" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.select_dialog_item, items);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Seleccione la imagen");
    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) { // pick from
            // camera
            if (item == 0) {
                /**
                 * To take a photo from camera, pass intent action
                 * ‘MediaStore.ACTION_IMAGE_CAPTURE‘ to open the camera app.
                 */
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                /**
                 * Also specify the Uri to save the image on specified path
                 * and file name. Note that this Uri variable also used by
                 * gallery app to hold the selected image path.
                 */
                mImageCaptureUri = Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), "tmp_avatar_"
                        + String.valueOf(System.currentTimeMillis())
                        + ".jpg"));

                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        mImageCaptureUri);

                try {
                    intent.putExtra("return-data", true);

                    startActivityForResult(intent, PICK_FROM_CAMERA);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                // pick from file
                /**
                 * To select an image from existing files, use
                 * Intent.createChooser to open image chooser. Android will
                 * automatically display a list of supported applications,
                 * such as image gallery or file manager.
                 */
                Intent intent = new Intent();

                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(Intent.createChooser(intent,
                        "Complete action using"), PICK_FROM_FILE);
            }
        }
    });

    builder.show();
}

public class CropOptionAdapter extends ArrayAdapter<CropOption> {
    private ArrayList<CropOption> mOptions;
    private LayoutInflater mInflater;

    public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
        super(context, R.layout.crop_selector, options);

        mOptions = options;

        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup group) {
        if (convertView == null)
            convertView = mInflater.inflate(R.layout.crop_selector, null);

        CropOption item = mOptions.get(position);

        if (item != null) {
            ((ImageView) convertView.findViewById(R.id.iv_icon))
                    .setImageDrawable(item.icon);
            ((TextView) convertView.findViewById(R.id.tv_name))
                    .setText(item.title);

            return convertView;
        }

        return null;
    }
}

public class CropOption {
    public CharSequence title;
    public Drawable icon;
    public Intent appIntent;
}


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK)
        return;

    switch (requestCode) {
        case PICK_FROM_CAMERA:
            /**
             * After taking a picture, do the crop
             */
            doCrop();

            break;

        case PICK_FROM_FILE:
            /**
             * After selecting image from files, save the selected path
             */
            mImageCaptureUri = data.getData();

            doCrop();

            break;

        case CROP_FROM_CAMERA:
            Bundle extras = data.getExtras();
            /**
             * After cropping the image, get the bitmap of the cropped image and
             * display it on imageview.
             */
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                //Uri imageUri = extras.getParcelable("data");
                profilePicture = photo;
                iv_profile.setImageBitmap(photo);
                IMAGE_STATUS = true;




            }

            File f = new File(mImageCaptureUri.getPath());
            /**
             * Delete the temporary image
             */
            if (f.exists())
                f.delete();

            break;

    }
}

private void doCrop() {
    final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
    /**
     * Open image crop app by starting an intent
     * ‘com.android.camera.action.CROP‘.
     */
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setType("image/*");

    /**
     * Check if there is image cropper app installed.
     */
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(
            intent, 0);

    int size = list.size();

    /**
     * If there is no image cropper app, display warning message
     */
    if (size == 0) {

        Toast.makeText(this, "Can not find image crop app",
                Toast.LENGTH_SHORT).show();

        return;
    } else {
        /**
         * Specify the image path, crop dimension and scale
         */
        intent.setData(mImageCaptureUri);

        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        /**
         * There is posibility when more than one image cropper app exist,
         * so we have to check for it first. If there is only one app, open
         * then app.
         */

        if (size == 1) {
            Intent i = new Intent(intent);
            ResolveInfo res = list.get(0);

            i.setComponent(new ComponentName(res.activityInfo.packageName,
                    res.activityInfo.name));

            startActivityForResult(i, CROP_FROM_CAMERA);
        } else {
            /**
             * If there are several app exist, create a custom chooser to
             * let user selects the app.
             */
            for (ResolveInfo res : list) {
                final CropOption co = new CropOption();

                co.title = getPackageManager().getApplicationLabel(
                        res.activityInfo.applicationInfo);
                co.icon = getPackageManager().getApplicationIcon(
                        res.activityInfo.applicationInfo);
                co.appIntent = new Intent(intent);

                co.appIntent
                        .setComponent(new ComponentName(
                                res.activityInfo.packageName,
                                res.activityInfo.name));

                cropOptions.add(co);
            }

            CropOptionAdapter adapter = new CropOptionAdapter(
                    getApplicationContext(), cropOptions);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Choose Crop App");
            builder.setAdapter(adapter,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            startActivityForResult(
                                    cropOptions.get(item).appIntent,
                                    CROP_FROM_CAMERA);
                        }
                    });

            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {

                    if (mImageCaptureUri != null) {
                        getContentResolver().delete(mImageCaptureUri, null,
                                null);
                        mImageCaptureUri = null;
                    }
                }
            });

            AlertDialog alert = builder.create();

            alert.show();
        }
    }

}

Esta es una de las partes donde se me pone en rojo:

 List<ResolveInfo> list = getPackageManager().queryIntentActivities(
            intent, 0);

En esta parte al cambiar "Registro" por el nombre de la clase genera un error, la clase es un fragment, y no tengo idea de que comando usar

  for (ResolveInfo res : list) {
                final Registro.CropOption co = new Registro.CropOption();

                co.title = getPackageManager().getApplicationLabel(
                        res.activityInfo.applicationInfo);
                co.icon = getPackageManager().getApplicationIcon(
                        res.activityInfo.applicationInfo);
                co.appIntent = new Intent(intent);

                co.appIntent
                        .setComponent(new ComponentName(
                                res.activityInfo.packageName,
                                res.activityInfo.name));

                cropOptions.add(co);

Las partes que estan en rojo me dicen que no se puede resolver el metodo.

1 respuesta 1

0

El metodo getPackageManager()pertenece al Context y un Fragment no es un Context, por lo que no encuentra el metodo.

Tienes que obtener el Activity(que es un Context) del Fragment con el método getActivity() y luego obtener el getPackgeManaget():

List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities(
            intent, 0);
1
  • Ok, eso ya lo hice y se supone que esa parte esta bien, el asunto ahora es en la ultima parte del codigo en la que hago lo siguiente: final Registro.CropOption co = new Registro.CropOption(); esa parte sigue arrojandome error Commented el 16 oct. 2017 a las 21:42

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.