0

I'm trying to take image from the camera or the gallery, this is the code that I'm running, but it's giving me an error with startActivityForResult :

public class NewPatient extends Fragment {  
    Button Takeimage, save, cancel;
    int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    ImageView imageview1;
    Uri imageUri;
    private Bitmap bitmap;
    MediaPlayer mp = new MediaPlayer();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myFragmentView = inflater.inflate(R.layout.activity_new_patient, container, false);


        imageview1 = (ImageView) myFragmentView.findViewById(R.id.imageNP);
        Takeimage = (Button) myFragmentView.findViewById(R.id.takeimg);
        save = (Button) myFragmentView.findViewById(R.id.save);
        cancel = (Button) myFragmentView.findViewById(R.id.cancel);

        Pakage = (Spinner) myFragmentView.findViewById(R.id.packages);
        Takeimage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
            selectImage();
        }
    });

    imageview1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            getActivity().openOptionsMenu();

        }
    });

    return myFragmentView;
}


private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }
}

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    imageview1.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    Uri selectedImageUri = data.getData();
    String[] projection = { MediaColumns.DATA };
    Cursor cursor = getActivity().managedQuery(selectedImageUri, projection, null, null,
            null);
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();

    String selectedImagePath = cursor.getString(column_index);

    Bitmap bm;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(selectedImagePath, options);
    final int REQUIRED_SIZE = 200;
    int scale = 1;
    while (options.outWidth / scale / 2 >= REQUIRED_SIZE
            && options.outHeight / scale / 2 >= REQUIRED_SIZE)
        scale *= 2;
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(selectedImagePath, options);

    imageview1.setImageBitmap(bm);
}

So, that was my code, but I don't know what's the problem, I can't understand it. Can anyone help me please?

Mousa Alfhaily
  • 1,260
  • 3
  • 20
  • 38
  • jaffa is right. you need to forward your result Activity to nested fragment. – Amol Sawant Sep 07 '15 at 09:44
  • 1
    possible duplicate of [onActivityResult not called in fragment android](http://stackoverflow.com/questions/20062840/onactivityresult-not-called-in-fragment-android) – Viktor Yakunin Sep 07 '15 at 09:52
  • duplicate of https://stackoverflow.com/questions/6147884/onactivityresult-is-not-being-called-in-fragment?rq=1 – Ashok Kumar Sep 07 '19 at 07:42

2 Answers2

1

I can think of two cases

If you're overriding onActivityResult() in your activity as well, make sure you call super.onActivityResult() in your activity

If your fragment is a nested fragment, you need to manually forward the result from parent fragment to nested fragment

Nick
  • 949
  • 1
  • 11
  • 31
1

this code for browse

case R.id.take_pic:
        startActivityForResult(new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE),
                TAKE_REQUEST);
        break;
    case R.id.browse_pic:

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_REQUEST);
        break;

in onActivity result

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == TAKE_REQUEST && resultCode == Activity.RESULT_OK) {
        pic = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(pic);

    }
    if (requestCode == SELECT_REQUEST && resultCode == Activity.RESULT_OK) {
        try {
            InputStream stream = getActivity().getContentResolver()
                    .openInputStream(data.getData());
            pic = BitmapFactory.decodeStream(stream);
            stream.close();
            imageView.setImageBitmap(pic);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Rahul Chaudhary
  • 1,059
  • 1
  • 6
  • 15