Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load image from camera to ImageView in a Fragment

I can load an image from camera into an ImageView when use an Activity:

btn_camera.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {

            Intent intent    = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                               "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
            try {
                intent.putExtra("return-data", true);
                startActivityForResult(intent, PICK_FROM_CAMERA);
                    } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                }

        }
    });

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

            switch (requestCode) {
                case PICK_FROM_CAMERA:

                      Bundle extras = data.getExtras();
                      if (extras != null) {      
                            Bitmap photo = extras.getParcelable("data");
                            img_profile.setImageBitmap(photo);
                      }
                      break;

                case LOAD_FROM_GALLERY: 

                    mImageCaptureUri = data.getData();
                    img_profile.setImageURI(mImageCaptureUri);

                    break;
            }
        }

However, when I use this in a Fragment (public class TabFragment1 extends Fragment) the RESULT_OK parameter is unknown to Android. I know the problem is that I am using a Fragment instead of an Activity, so how can I do it?

like image 666
Jani Bela Avatar asked Dec 26 '22 23:12

Jani Bela


1 Answers

the RESULT_OK parameter is unknown to Android

No, it is not.

RESULT_OK is unknown to Fragment, because RESULT_OK is a public static data member defined on Activity.

Hence, to refer to RESULT_OK from outside of Activity (or classes that inherit from Activity), use Activity.RESULT_OK.

like image 161
CommonsWare Avatar answered Jan 12 '23 21:01

CommonsWare