0

So i have 2 Activities, the first one is to launch camera before the second Activity start. After taking the camera, the ImageView on second Activities will changed by the photo ive taken. And if i click the ImageView, it will intent the camera and replacing the image from camera. However, i cant replace the image at ImageView and the resultCode always 0 everytime after taking picture.

here is first Activity

    @OnClick(R.id.fab_toko)
    private void create_ticket() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(Consts.MEDIA_TYPE_IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        // start the image capture Intent
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        startActivityForResult(intent, Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE);


    }
 public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
        //return FileProvider.getUriForFile(MainActivity.this, MainActivity.this.getApplicationContext().getPackageName(), getOutputMediaFile(type));

    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {
        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                Consts.IMAGE_DIRECTORY_NAME);

        //Creating an internal dir;
        File mDir = RumahkeduaApplication.getContext().getDir("ISS", Context.MODE_PRIVATE);
        //Internal Storage
        // File mediaInternalDir = new File(mDir,Consts.IMAGE_DIRECTORY_NAME);

        File mediaInternalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

        // Create the storage directory if it does not exist
        if (!mediaInternalDir.exists()) {
            if (!mediaInternalDir.mkdirs()) {
                Log.d(TAG, "Oops! Failed create "
                        + Consts.IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == Consts.MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaInternalDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");

        } else {
            return null;
        }

        return mediaFile;
    }


    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // save file url in bundle as it will be null on screen orientation
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // successfully captured the image

                comImage.compressImage(fileUri.toString());

                Intent mainIntent = new Intent(MainActivity.this, CreateTicketActivity.class);
                mainIntent.putExtra("id_user", login_user.getId_user());
                mainIntent.putExtra("string_uri", fileUri.toString());
                mainIntent.putExtra("ticket_type", "Toko Prima");
                MainActivity.this.startActivity(mainIntent);
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

And here is second Activity

    @OnClick(R.id.iv_post_photo)
    private void captureImage() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
//        if (!ticket_type.equals("Toko Prima")){
//            TODO
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(Consts.MEDIA_TYPE_IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        // start the image capture Intent
        startActivityForResult(intent, Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
        setResult(RESULT_OK);


//        }
    }
 public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                Consts.IMAGE_DIRECTORY_NAME);

        File mediaInternalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

        // Create the storage directory if it does not exist
        if (!mediaInternalDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "Oops! Failed create "
                        + Consts.IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == Consts.MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else {
            return null;
        }

        return mediaFile;
    }


    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // save file url in bundle as it will be null on screen orientation
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
//        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        if (requestCode == Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // successfully captured the image
                comImage.compressImage(fileUri.toString());

                Picasso.with(this).load(fileUri).fit().centerCrop().into(ivPhoto);
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture0
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
}

storage permission already checked on manifest

  • 1
    Possible duplicate of [Camera always returns resultCode as 0](https://stackoverflow.com/questions/10831562/camera-always-returns-resultcode-as-0) – Vikasdeep Singh Aug 28 '18 at 07:41
  • launch mode didnt resolve the problem – Philip Sultan Aug 28 '18 at 07:46
  • As a side note `Uri.fromFile` will crash on Android N use `FileProvider`. – ADM Aug 28 '18 at 07:47
  • One activity uses **mediaInternalDir**, the second – **mediaStorageDir**. It isn't surprising that the results are different. Actually, there is no reason to have all this code duplicated. You can use same `getOutputMediaFileUri()` in both activities. – Alex Cohn Aug 28 '18 at 13:22
  • oh thanks i didnt notice that. The camera now works – Philip Sultan Aug 29 '18 at 01:55

1 Answers1

0

i used a combination of answers to make it work so i ended up with this code:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Date dat = Calendar.getInstance().getTime();
        SimpleDateFormat simpleDate =  new SimpleDateFormat("yyyy-mm-dd-hh:mm:ss");
        String nameFoto = simpleDate.format(dat) + ".png";
        String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ File.separator +nameFoto;
        File ff = new File(filename);

        try {
            ff.createNewFile();
            //imageUri = Uri.fromFile(ff);
            imageUri = FileProvider.getUriForFile(IngresarFactura.this, BuildConfig.APPLICATION_ID + ".provider",ff);
            //imageUri = new Uri(filename).
            if (imageUri.getPath() == null){
                mensaje.setText(filename+ " Error path es nulo.");
            }
            cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);

            //COMPATIBILITY
            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP) {
                cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } else {
                List<ResolveInfo> resInfoList = IngresarFactura.this.getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    IngresarFactura.this.grantUriPermission(packageName, imageUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            }
            //COMPATIBILITY
            activityResultLaunch.launch(cameraIntent);
        }

you also have to do this as answered here:

https://stackoverflow.com/a/45751453/16645882