问:
How to pick image for crop from camera or gallery in Android 7.0?
Pick image for crop from gallery and camera it's done for below Android 7.0 but in Android Nought it crashes in camera. I use fileprovider for it but doesn't work.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button mBtn;
private Context context;
private static final int SELECT_PICTURE_CAMARA = 101, SELECT_PICTURE = 201, CROP_IMAGE = 301;
private Uri outputFileUri;
String mCurrentPhotoPath;
private Uri selectedImageUri;
private File finalFile = null;
private ImageView imageView;
private PermissionUtil permissionUtil;
Uri fileUri;
File file = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mBtn = (Button) findViewById(R.id.btn_img);
    imageView = (ImageView) findViewById(R.id.img_photo);
    permissionUtil = new PermissionUtil();
    mBtn.setOnClickListener(this);
    context = this;
}

@Override
public void onClick(View view) {
    selectImageOption();
}

private void selectImageOption() {
    final CharSequence[] items = {"Capture Photo", "Choose from Gallery", "Cancel"};

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Capture Photo")) {
                if (permissionUtil.checkMarshMellowPermission()) {
                    if (permissionUtil.verifyPermissions(MainActivity.this, permissionUtil.getCameraPermissions()))
                        onClickCamera();
                    else
                        ActivityCompat.requestPermissions(MainActivity.this, permissionUtil.getCameraPermissions(), SELECT_PICTURE_CAMARA);
                } else
                    onClickCamera();
            } else if (items[item].equals("Choose from Gallery")) {
                if (permissionUtil.checkMarshMellowPermission()) {
                    if (permissionUtil.verifyPermissions(MainActivity.this, permissionUtil.getGalleryPermissions()))
                        onClickGallery();
                    else
                        ActivityCompat.requestPermissions(MainActivity.this, permissionUtil.getGalleryPermissions(), SELECT_PICTURE);
                } else
                    onClickGallery();
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

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

    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            selectedImageUri = data.getData();
            cropImage(selectedImageUri);

        } else if (requestCode == CROP_IMAGE) {

            Uri imageUri = Uri.parse(mCurrentPhotoPath);
            File file = new File(imageUri.getPath());
            try {
                InputStream ims = new FileInputStream(file);
                imageView.setImageBitmap(BitmapFactory.decodeStream(ims));
            } catch (FileNotFoundException e) {
                return;
            }

        } else if (requestCode == SELECT_PICTURE_CAMARA && resultCode == Activity.RESULT_OK) {
            cropImage1();
        }
    }
}

private void onClickCamera() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
       /* File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
        }
        if (photoFile != null) {

            Uri photoURI;
            if (Build.VERSION.SDK_INT >= 24) {
                photoURI = FileProvider.getUriForFile(MainActivity.this,
                        BuildConfig.APPLICATION_ID + ".fileprovider", photoFile);
            } else {
                photoURI = Uri.fromFile(photoFile);
            }
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, SELECT_PICTURE_CAMARA);

        }*/

        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
        fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(takePictureIntent, SELECT_PICTURE_CAMARA);

    } else {
        Toast.makeText(this, getString(R.string.error_no_camera), Toast.LENGTH_LONG).show();
    }
}

private void onClickGallery() {
    List<Intent> targets = new ArrayList<>();
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_PICK);
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    List<ResolveInfo> candidates = getApplicationContext().getPackageManager().queryIntentActivities(intent, 0);

    for (ResolveInfo candidate : candidates) {
        String packageName = candidate.activityInfo.packageName;
        if (!packageName.equals("com.google.android.apps.photos") && !packageName.equals("com.google.android.apps.plus") && !packageName.equals("com.android.documentsui")) {
            Intent iWantThis = new Intent();
            iWantThis.setType("image/*");
            iWantThis.setAction(Intent.ACTION_PICK);
            iWantThis.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            iWantThis.setPackage(packageName);
            targets.add(iWantThis);
        }
    }
    if (targets.size() > 0) {
        Intent chooser = Intent.createChooser(targets.remove(0), "Select Picture");
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targets.toArray(new Parcelable[targets.size()]));
        startActivityForResult(chooser, SELECT_PICTURE);
    } else {
        Intent intent1 = new Intent(Intent.ACTION_PICK);
        intent1.setType("image/*");
        startActivityForResult(Intent.createChooser(intent1, "Select Picture"), SELECT_PICTURE);
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";

    File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    if (Build.VERSION.SDK_INT >= 24) {
        mCurrentPhotoPath = String.valueOf(FileProvider.getUriForFile(MainActivity.this,
                BuildConfig.APPLICATION_ID + ".provider", image));
    } else {
        mCurrentPhotoPath = String.valueOf(Uri.fromFile(image));
    }

    return image;
}

/*private Uri createImageUri(){
    ContentResolver contentResolver=getContentResolver();
    ContentValues cv=new ContentValues();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    cv.put(MediaStore.Images.Media.TITLE,timeStamp);
    return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,cv);
}*/

private void cropImage(Uri selectedImageUri) {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(selectedImageUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1.5);
    cropIntent.putExtra("return-data", true);

    outputFileUri = Uri.fromFile(createCropFile());
    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(cropIntent, CROP_IMAGE);
}

private void cropImage1() {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(fileUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1.5);
    cropIntent.putExtra("return-data", true);

    if (Build.VERSION.SDK_INT >= 24) {
        outputFileUri = FileProvider.getUriForFile(MainActivity.this,
                BuildConfig.APPLICATION_ID + ".provider", createCropFile());

    } else
        outputFileUri = Uri.fromFile(createCropFile());

    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(cropIntent, CROP_IMAGE);

   /* ContentValues values = new ContentValues(1);
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
    outputFileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(cropIntent, CROP_IMAGE);*/
}

private File createCropFile() {
    File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    //  path = path + (timeStamp + "1jpg");

    try {
        file = File.createTempFile(timeStamp, ".jpg", storageDir);
    } catch (IOException e) {
        e.printStackTrace();
    }

    /*if (Build.VERSION.SDK_INT >= 24)
        mCurrentPhotoPath = String.valueOf(FileProvider.getUriForFile(MainActivity.this,
                BuildConfig.APPLICATION_ID + ".provider", file));
    else*/
    mCurrentPhotoPath = String.valueOf(Uri.fromFile(file));
    return file;
}
}
</code>```

this work in all device but not in >= android 7.0 Nought device

答:
I got the solution.Posting my answer.

In MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

@BindView(R.id.img_camera)
CircleImageView mImgCamera;

private ChoosePhoto choosePhoto=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
}

@OnClick(R.id.img_camera)
public void onViewClicked() {
    choosePhoto = new ChoosePhoto(this);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == ChoosePhoto.CHOOSE_PHOTO_INTENT) {
            if (data != null && data.getData() != null) {
                choosePhoto.handleGalleryResult(data);
            } else {
                choosePhoto.handleCameraResult(choosePhoto.getCameraUri());
            }
        }else if (requestCode == ChoosePhoto.SELECTED_IMG_CROP) {
            mImgCamera.setImageURI(choosePhoto.getCropImageUrl());
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == ChoosePhoto.SELECT_PICTURE_CAMERA) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            choosePhoto.showAlertDialog();
    }
}
}
</code>```

ChoosePhoto.java

```<code>public class ChoosePhoto {

public static int CHOOSE_PHOTO_INTENT = 101;
public static int SELECTED_IMG_CROP = 102;
public static int SELECT_PICTURE_CAMERA = 103;
public static int currentAndroidDeviceVersion = Build.VERSION.SDK_INT;

private int ASPECT_X = 1;
private int ASPECT_Y = 1;
private int OUT_PUT_X = 300;
private int OUT_PUT_Y = 300;
private boolean SCALE = true;

private Uri cropPictureUrl, selectedImageUri = null, cameraUrl = null;
private Context mContext;

public ChoosePhoto(Context context) {
    mContext = context;
    init();
}

private void init() {
    PermissionUtil permissionUtil = new PermissionUtil();

    if (permissionUtil.checkMarshMellowPermission()) {
        if (permissionUtil.verifyPermissions(mContext, permissionUtil.getCameraPermissions()) && permissionUtil.verifyPermissions(mContext, permissionUtil.getGalleryPermissions()))
            showAlertDialog();
        else {
            ActivityCompat.requestPermissions((Activity) mContext, permissionUtil.getCameraPermissions(), SELECT_PICTURE_CAMERA);
        }
    } else {
        showAlertDialog();
    }
}

public void showAlertDialog() {
    final Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    galleryIntent.setType("image/*");

    cameraUrl = FileUtil.getInstance(mContext).createImageUri();
    //Create any other intents you want
    final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUrl);

    //Add them to an intent array
    Intent[] intents = new Intent[]{cameraIntent};

    //Create a choose from your first intent then pass in the intent array
    final Intent chooserIntent = Intent.createChooser(galleryIntent, mContext.getString(R.string.choose_photo_title));
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);

    ((Activity) mContext).startActivityForResult(chooserIntent, CHOOSE_PHOTO_INTENT);
}

// Change this method(edited)
public void handleGalleryResult(Intent data) {
    try {
        cropPictureUrl = Uri.fromFile(FileUtil.getInstance(mContext)
                .createImageTempFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));
        String realPathFromURI = FileUtil.getRealPathFromURI(mContext, data.getData());
        File file = new File(realPathFromURI == null ? getImageUrlWithAuthority(mContext, data.getData()) : realPathFromURI);
        if (file.exists()) {
            if (currentAndroidDeviceVersion > 23) {
                cropImage(FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", file), cropPictureUrl);

            } else {
                cropImage(Uri.fromFile(file), cropPictureUrl);
            }

        } else {
            cropImage(data.getData(), cropPictureUrl);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String getImageUrlWithAuthority(Context context, Uri uri) {
    InputStream is = null;
    if (uri.getAuthority() != null) {
        try {
            is = context.getContentResolver().openInputStream(uri);
            Bitmap bmp = BitmapFactory.decodeStream(is);
            return writeToTempImageAndGetPathUri(context, bmp).toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

public static Uri writeToTempImageAndGetPathUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public void handleCameraResult(Uri cameraPictureUrl) {
    try {
        cropPictureUrl = Uri.fromFile(FileUtil.getInstance(mContext)
                .createImageTempFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));

        cropImage(cameraPictureUrl, cropPictureUrl);
    } catch (IOException e) {
        e.printStackTrace();

    }

}

public Uri getCameraUri() {
    return cameraUrl;
}

public Uri getCropImageUrl() {
    return selectedImageUri;
}

private void cropImage(final Uri sourceImage, Uri destinationImage) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    intent.setType("image/*");

    List<ResolveInfo> list = mContext.getPackageManager().queryIntentActivities(intent, 0);
    int size = list.size();
    if (size == 0) {
        //Utils.showToast(mContext, mContext.getString(R.string.error_cant_select_cropping_app));
        selectedImageUri = sourceImage;
        intent.putExtra(MediaStore.EXTRA_OUTPUT, sourceImage);
        ((Activity) mContext).startActivityForResult(intent, SELECTED_IMG_CROP);
        return;
    } else {
        intent.setDataAndType(sourceImage, "image/*");
        intent.putExtra("aspectX", ASPECT_X);
        intent.putExtra("aspectY", ASPECT_Y);
        intent.putExtra("outputY", OUT_PUT_Y);
        intent.putExtra("outputX", OUT_PUT_X);
        intent.putExtra("scale", SCALE);

        //intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, destinationImage);
        selectedImageUri = destinationImage;
        if (size == 1) {
            Intent i = new Intent(intent);
            ResolveInfo res = list.get(0);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            ((Activity) mContext).startActivityForResult(intent, SELECTED_IMG_CROP);
        } else {
            Intent i = new Intent(intent);
            i.putExtra(Intent.EXTRA_INITIAL_INTENTS, list.toArray(new Parcelable[list.size()]));
            ((Activity) mContext).startActivityForResult(intent, SELECTED_IMG_CROP);
        }
    }
}
}
</code>```

FileUtil.java

```<code>public class FileUtil {
private static FileUtil sSingleton;
private Context context;

private FileUtil(Context ctx) {
    context = ctx;
}

/**
 * Gets instance.
 *
 * @param ctx the ctx
 * @return the instance
 */
public static FileUtil getInstance(Context ctx) {
    if (sSingleton == null) {
        synchronized (FileUtil.class) {
            sSingleton = new FileUtil(ctx);
        }
    }
    return sSingleton;
}

public Uri createImageUri() {
    ContentResolver contentResolver = context.getContentResolver();
    ContentValues cv = new ContentValues();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    cv.put(MediaStore.Images.Media.TITLE, timeStamp);
    return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
}

/**
 * Create image temp file file.
 *
 * @param filePathDir the file path dir
 * @return the file
 * @throws IOException the io exception
 */
@SuppressLint("SimpleDateFormat")
public File createImageTempFile(File filePathDir) throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    String imageFileName = "JPEG_" + timeStamp + "_";
    return File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            filePathDir      /* directory */
    );
}

public static  String getUploadFileName() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
    Date date = new Date();
    return String.format("profile_%s.png", sdf.format(date));
}

 //add this code(edited)
 //get Path
  @TargetApi(Build.VERSION_CODES.KITKAT)
  public static String getRealPathFromURI(Context context, final Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    } else
        return getRealPathFromURIDB(uri);

    return null;
}

/**
 * Gets real path from uri.
 *
 * @param contentUri the content uri
 * @return the real path from uri
 */
private static String getRealPathFromURIDB(Uri contentUri) {
    Cursor cursor = context.getContentResolver().query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        String realPath = cursor.getString(index);
        cursor.close();
        return realPath;
    }
}

/**
 * Gets data column.
 *
 * @param uri           the uri
 * @param selection     the selection
 * @param selectionArgs the selection args
 * @return the data column
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

/**
 * Is external storage document boolean.
 *
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * Is downloads document boolean.
 *
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * Is media document boolean.
 *
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * Is google photos uri boolean.
 *
 * @param uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
  }
</code>```

PermissionUtil.java

```<code>public class PermissionUtil {
      private String[] galleryPermissions = {
          "android.permission.WRITE_EXTERNAL_STORAGE",
          "android.permission.READ_EXTERNAL_STORAGE"
      };

private String[] cameraPermissions = {
        "android.permission.CAMERA",
        "android.permission.WRITE_EXTERNAL_STORAGE",
        "android.permission.READ_EXTERNAL_STORAGE"
};

public String[] getGalleryPermissions(){
    return galleryPermissions;
}

public String[] getCameraPermissions() {
    return cameraPermissions;
}

public boolean verifyPermissions(Context context, String[] grantResults) {
    for (String result : grantResults) {
        if (ActivityCompat.checkSelfPermission(context, result) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
    }
    return true;
}

public boolean checkMarshMellowPermission(){
    return(Build.VERSION.SDK_INT> Build.VERSION_CODES.LOLLIPOP_MR1);
}

public static void showPermissionDialog(Context mContext,String msg){
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.DatePicker);
    builder.setTitle("Need Permission");
    builder.setMessage(msg);
    builder.setPositiveButton(mContext.getString(R.string.invitation_yes), (dialogInterface, i) -> {
        dialogInterface.dismiss();
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", mContext.getPackageName(), null);
        intent.setData(uri);
        (mContext).startActivity(intent);
    });

    builder.setNegativeButton(mContext.getString(R.string.invitation_del_no), (dialogInterface, i) -> {
        dialogInterface.dismiss();
    });
    builder.show();
}
</code>```

}

provide_paths.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Pick image for crop from gallery and camera it's done for below Android 7.0 but in Android Nought it crashes in camera. I use fileprovider for it but doesn't work.

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button mBtn;
private Context context;
private static final int SELECT_PICTURE_CAMARA = 101, SELECT_PICTURE = 201, CROP_IMAGE = 301;
private Uri outputFileUri;
String mCurrentPhotoPath;
private Uri selectedImageUri;
private File finalFile = null;
private ImageView imageView;
private PermissionUtil permissionUtil;
Uri fileUri;
File file = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mBtn = (Button) findViewById(R.id.btn_img);
    imageView = (ImageView) findViewById(R.id.img_photo);
    permissionUtil = new PermissionUtil();
    mBtn.setOnClickListener(this);
    context = this;
}

@Override
public void onClick(View view) {
    selectImageOption();
}

private void selectImageOption() {
    final CharSequence[] items = {"Capture Photo", "Choose from Gallery", "Cancel"};

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Capture Photo")) {
                if (permissionUtil.checkMarshMellowPermission()) {
                    if (permissionUtil.verifyPermissions(MainActivity.this, permissionUtil.getCameraPermissions()))
                        onClickCamera();
                    else
                        ActivityCompat.requestPermissions(MainActivity.this, permissionUtil.getCameraPermissions(), SELECT_PICTURE_CAMARA);
                } else
                    onClickCamera();
            } else if (items[item].equals("Choose from Gallery")) {
                if (permissionUtil.checkMarshMellowPermission()) {
                    if (permissionUtil.verifyPermissions(MainActivity.this, permissionUtil.getGalleryPermissions()))
                        onClickGallery();
                    else
                        ActivityCompat.requestPermissions(MainActivity.this, permissionUtil.getGalleryPermissions(), SELECT_PICTURE);
                } else
                    onClickGallery();
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

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

    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            selectedImageUri = data.getData();
            cropImage(selectedImageUri);

        } else if (requestCode == CROP_IMAGE) {

            Uri imageUri = Uri.parse(mCurrentPhotoPath);
            File file = new File(imageUri.getPath());
            try {
                InputStream ims = new FileInputStream(file);
                imageView.setImageBitmap(BitmapFactory.decodeStream(ims));
            } catch (FileNotFoundException e) {
                return;
            }

        } else if (requestCode == SELECT_PICTURE_CAMARA && resultCode == Activity.RESULT_OK) {
            cropImage1();
        }
    }
}

private void onClickCamera() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
       /* File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
        }
        if (photoFile != null) {

            Uri photoURI;
            if (Build.VERSION.SDK_INT >= 24) {
                photoURI = FileProvider.getUriForFile(MainActivity.this,
                        BuildConfig.APPLICATION_ID + ".fileprovider", photoFile);
            } else {
                photoURI = Uri.fromFile(photoFile);
            }
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, SELECT_PICTURE_CAMARA);

        }*/

        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
        fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(takePictureIntent, SELECT_PICTURE_CAMARA);

    } else {
        Toast.makeText(this, getString(R.string.error_no_camera), Toast.LENGTH_LONG).show();
    }
}

private void onClickGallery() {
    List<Intent> targets = new ArrayList<>();
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_PICK);
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    List<ResolveInfo> candidates = getApplicationContext().getPackageManager().queryIntentActivities(intent, 0);

    for (ResolveInfo candidate : candidates) {
        String packageName = candidate.activityInfo.packageName;
        if (!packageName.equals("com.google.android.apps.photos") && !packageName.equals("com.google.android.apps.plus") && !packageName.equals("com.android.documentsui")) {
            Intent iWantThis = new Intent();
            iWantThis.setType("image/*");
            iWantThis.setAction(Intent.ACTION_PICK);
            iWantThis.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            iWantThis.setPackage(packageName);
            targets.add(iWantThis);
        }
    }
    if (targets.size() > 0) {
        Intent chooser = Intent.createChooser(targets.remove(0), "Select Picture");
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targets.toArray(new Parcelable[targets.size()]));
        startActivityForResult(chooser, SELECT_PICTURE);
    } else {
        Intent intent1 = new Intent(Intent.ACTION_PICK);
        intent1.setType("image/*");
        startActivityForResult(Intent.createChooser(intent1, "Select Picture"), SELECT_PICTURE);
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";

    File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    if (Build.VERSION.SDK_INT >= 24) {
        mCurrentPhotoPath = String.valueOf(FileProvider.getUriForFile(MainActivity.this,
                BuildConfig.APPLICATION_ID + ".provider", image));
    } else {
        mCurrentPhotoPath = String.valueOf(Uri.fromFile(image));
    }

    return image;
}

/*private Uri createImageUri(){
    ContentResolver contentResolver=getContentResolver();
    ContentValues cv=new ContentValues();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    cv.put(MediaStore.Images.Media.TITLE,timeStamp);
    return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,cv);
}*/

private void cropImage(Uri selectedImageUri) {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(selectedImageUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1.5);
    cropIntent.putExtra("return-data", true);

    outputFileUri = Uri.fromFile(createCropFile());
    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(cropIntent, CROP_IMAGE);
}

private void cropImage1() {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(fileUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1.5);
    cropIntent.putExtra("return-data", true);

    if (Build.VERSION.SDK_INT >= 24) {
        outputFileUri = FileProvider.getUriForFile(MainActivity.this,
                BuildConfig.APPLICATION_ID + ".provider", createCropFile());

    } else
        outputFileUri = Uri.fromFile(createCropFile());

    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(cropIntent, CROP_IMAGE);

   /* ContentValues values = new ContentValues(1);
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
    outputFileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(cropIntent, CROP_IMAGE);*/
}

private File createCropFile() {
    File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    //  path = path + (timeStamp + "1jpg");

    try {
        file = File.createTempFile(timeStamp, ".jpg", storageDir);
    } catch (IOException e) {
        e.printStackTrace();
    }

    /*if (Build.VERSION.SDK_INT >= 24)
        mCurrentPhotoPath = String.valueOf(FileProvider.getUriForFile(MainActivity.this,
                BuildConfig.APPLICATION_ID + ".provider", file));
    else*/
    mCurrentPhotoPath = String.valueOf(Uri.fromFile(file));
    return file;
}
}

this work in all device but not in >= android 7.0 Nought device

Body:
I got the solution.Posting my answer.

In MainActivity.java

public class MainActivity extends AppCompatActivity {

@BindView(R.id.img_camera)
CircleImageView mImgCamera;

private ChoosePhoto choosePhoto=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
}

@OnClick(R.id.img_camera)
public void onViewClicked() {
    choosePhoto = new ChoosePhoto(this);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == ChoosePhoto.CHOOSE_PHOTO_INTENT) {
            if (data != null && data.getData() != null) {
                choosePhoto.handleGalleryResult(data);
            } else {
                choosePhoto.handleCameraResult(choosePhoto.getCameraUri());
            }
        }else if (requestCode == ChoosePhoto.SELECTED_IMG_CROP) {
            mImgCamera.setImageURI(choosePhoto.getCropImageUrl());
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == ChoosePhoto.SELECT_PICTURE_CAMERA) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            choosePhoto.showAlertDialog();
    }
}
}

ChoosePhoto.java

public class ChoosePhoto {

public static int CHOOSE_PHOTO_INTENT = 101;
public static int SELECTED_IMG_CROP = 102;
public static int SELECT_PICTURE_CAMERA = 103;
public static int currentAndroidDeviceVersion = Build.VERSION.SDK_INT;

private int ASPECT_X = 1;
private int ASPECT_Y = 1;
private int OUT_PUT_X = 300;
private int OUT_PUT_Y = 300;
private boolean SCALE = true;

private Uri cropPictureUrl, selectedImageUri = null, cameraUrl = null;
private Context mContext;

public ChoosePhoto(Context context) {
    mContext = context;
    init();
}

private void init() {
    PermissionUtil permissionUtil = new PermissionUtil();

    if (permissionUtil.checkMarshMellowPermission()) {
        if (permissionUtil.verifyPermissions(mContext, permissionUtil.getCameraPermissions()) && permissionUtil.verifyPermissions(mContext, permissionUtil.getGalleryPermissions()))
            showAlertDialog();
        else {
            ActivityCompat.requestPermissions((Activity) mContext, permissionUtil.getCameraPermissions(), SELECT_PICTURE_CAMERA);
        }
    } else {
        showAlertDialog();
    }
}

public void showAlertDialog() {
    final Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    galleryIntent.setType("image/*");

    cameraUrl = FileUtil.getInstance(mContext).createImageUri();
    //Create any other intents you want
    final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUrl);

    //Add them to an intent array
    Intent[] intents = new Intent[]{cameraIntent};

    //Create a choose from your first intent then pass in the intent array
    final Intent chooserIntent = Intent.createChooser(galleryIntent, mContext.getString(R.string.choose_photo_title));
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);

    ((Activity) mContext).startActivityForResult(chooserIntent, CHOOSE_PHOTO_INTENT);
}

// Change this method(edited)
public void handleGalleryResult(Intent data) {
    try {
        cropPictureUrl = Uri.fromFile(FileUtil.getInstance(mContext)
                .createImageTempFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));
        String realPathFromURI = FileUtil.getRealPathFromURI(mContext, data.getData());
        File file = new File(realPathFromURI == null ? getImageUrlWithAuthority(mContext, data.getData()) : realPathFromURI);
        if (file.exists()) {
            if (currentAndroidDeviceVersion > 23) {
                cropImage(FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", file), cropPictureUrl);

            } else {
                cropImage(Uri.fromFile(file), cropPictureUrl);
            }

        } else {
            cropImage(data.getData(), cropPictureUrl);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String getImageUrlWithAuthority(Context context, Uri uri) {
    InputStream is = null;
    if (uri.getAuthority() != null) {
        try {
            is = context.getContentResolver().openInputStream(uri);
            Bitmap bmp = BitmapFactory.decodeStream(is);
            return writeToTempImageAndGetPathUri(context, bmp).toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

public static Uri writeToTempImageAndGetPathUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public void handleCameraResult(Uri cameraPictureUrl) {
    try {
        cropPictureUrl = Uri.fromFile(FileUtil.getInstance(mContext)
                .createImageTempFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));

        cropImage(cameraPictureUrl, cropPictureUrl);
    } catch (IOException e) {
        e.printStackTrace();

    }

}

public Uri getCameraUri() {
    return cameraUrl;
}

public Uri getCropImageUrl() {
    return selectedImageUri;
}

private void cropImage(final Uri sourceImage, Uri destinationImage) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    intent.setType("image/*");

    List<ResolveInfo> list = mContext.getPackageManager().queryIntentActivities(intent, 0);
    int size = list.size();
    if (size == 0) {
        //Utils.showToast(mContext, mContext.getString(R.string.error_cant_select_cropping_app));
        selectedImageUri = sourceImage;
        intent.putExtra(MediaStore.EXTRA_OUTPUT, sourceImage);
        ((Activity) mContext).startActivityForResult(intent, SELECTED_IMG_CROP);
        return;
    } else {
        intent.setDataAndType(sourceImage, "image/*");
        intent.putExtra("aspectX", ASPECT_X);
        intent.putExtra("aspectY", ASPECT_Y);
        intent.putExtra("outputY", OUT_PUT_Y);
        intent.putExtra("outputX", OUT_PUT_X);
        intent.putExtra("scale", SCALE);

        //intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, destinationImage);
        selectedImageUri = destinationImage;
        if (size == 1) {
            Intent i = new Intent(intent);
            ResolveInfo res = list.get(0);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            ((Activity) mContext).startActivityForResult(intent, SELECTED_IMG_CROP);
        } else {
            Intent i = new Intent(intent);
            i.putExtra(Intent.EXTRA_INITIAL_INTENTS, list.toArray(new Parcelable[list.size()]));
            ((Activity) mContext).startActivityForResult(intent, SELECTED_IMG_CROP);
        }
    }
}
}

FileUtil.java

public class FileUtil {
private static FileUtil sSingleton;
private Context context;

private FileUtil(Context ctx) {
    context = ctx;
}

/**
 * Gets instance.
 *
 * @param ctx the ctx
 * @return the instance
 */
public static FileUtil getInstance(Context ctx) {
    if (sSingleton == null) {
        synchronized (FileUtil.class) {
            sSingleton = new FileUtil(ctx);
        }
    }
    return sSingleton;
}

public Uri createImageUri() {
    ContentResolver contentResolver = context.getContentResolver();
    ContentValues cv = new ContentValues();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    cv.put(MediaStore.Images.Media.TITLE, timeStamp);
    return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
}

/**
 * Create image temp file file.
 *
 * @param filePathDir the file path dir
 * @return the file
 * @throws IOException the io exception
 */
@SuppressLint("SimpleDateFormat")
public File createImageTempFile(File filePathDir) throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    String imageFileName = "JPEG_" + timeStamp + "_";
    return File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            filePathDir      /* directory */
    );
}

public static  String getUploadFileName() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
    Date date = new Date();
    return String.format("profile_%s.png", sdf.format(date));
}

 //add this code(edited)
 //get Path
  @TargetApi(Build.VERSION_CODES.KITKAT)
  public static String getRealPathFromURI(Context context, final Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    } else
        return getRealPathFromURIDB(uri);

    return null;
}

/**
 * Gets real path from uri.
 *
 * @param contentUri the content uri
 * @return the real path from uri
 */
private static String getRealPathFromURIDB(Uri contentUri) {
    Cursor cursor = context.getContentResolver().query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        String realPath = cursor.getString(index);
        cursor.close();
        return realPath;
    }
}

/**
 * Gets data column.
 *
 * @param uri           the uri
 * @param selection     the selection
 * @param selectionArgs the selection args
 * @return the data column
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

/**
 * Is external storage document boolean.
 *
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * Is downloads document boolean.
 *
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * Is media document boolean.
 *
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * Is google photos uri boolean.
 *
 * @param uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
  }

PermissionUtil.java

public class PermissionUtil {
      private String[] galleryPermissions = {
          "android.permission.WRITE_EXTERNAL_STORAGE",
          "android.permission.READ_EXTERNAL_STORAGE"
      };

private String[] cameraPermissions = {
        "android.permission.CAMERA",
        "android.permission.WRITE_EXTERNAL_STORAGE",
        "android.permission.READ_EXTERNAL_STORAGE"
};

public String[] getGalleryPermissions(){
    return galleryPermissions;
}

public String[] getCameraPermissions() {
    return cameraPermissions;
}

public boolean verifyPermissions(Context context, String[] grantResults) {
    for (String result : grantResults) {
        if (ActivityCompat.checkSelfPermission(context, result) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
    }
    return true;
}

public boolean checkMarshMellowPermission(){
    return(Build.VERSION.SDK_INT> Build.VERSION_CODES.LOLLIPOP_MR1);
}

public static void showPermissionDialog(Context mContext,String msg){
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.DatePicker);
    builder.setTitle("Need Permission");
    builder.setMessage(msg);
    builder.setPositiveButton(mContext.getString(R.string.invitation_yes), (dialogInterface, i) -> {
        dialogInterface.dismiss();
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", mContext.getPackageName(), null);
        intent.setData(uri);
        (mContext).startActivity(intent);
    });

    builder.setNegativeButton(mContext.getString(R.string.invitation_del_no), (dialogInterface, i) -> {
        dialogInterface.dismiss();
    });
    builder.show();
}

}

provide_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>


来源: stackexchange

问:
How to integrate cropping variants in image manipulation tool in tx_news extension?
There's an awesome feature in TYPO3 8.7 called cropping variants in image manipulation tool. Details informations can be found in official feature description #75880. Thanks to this we can allow back-end user to crop one image in multiple variants, for exampple: for mobile and desktop. See image below.

Image from: https://techblog.sitegeist.de/responsive-images-with-typo3-8-7/

Configuration can be done in TCA:

```<code>'config' => [
 'type' => 'imageManipulation',
 'cropVariants' => [
     'mobile' => [
         'title' => 'LLL:EXT:ext_key/Resources/Private/Language/locallang.xlf:imageManipulation.mobile',
         'allowedAspectRatios' => [
             '4:3' => [
                 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.4_3',
                 'value' => 4 / 3
             ],
             'NaN' => [
                 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.free',
                 'value' => 0.0
             ],
         ],
     ],
     'desktop' => [
         'title' => 'LLL:EXT:ext_key/Resources/Private/Language/locallang.xlf:imageManipulation.desktop',
         'allowedAspectRatios' => [
             '4:3' => [
                 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.4_3',
                 'value' => 4 / 3
             ],
             'NaN' => [
                 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.free',
                 'value' => 0.0
             ],
         ],
     ],
 ]
</code>```

]

I'm trying to integrate it into tx_news. I want to use existing field called fal_media. The configuration of this field you can find in the source file of tx_news in GitHub. Screenshot of the code snippet below:

Somebody have an idea how cropping variants in image manipulation can be implemented in tx_news extension for field fal_media?

答: simply add cropVariant="mobile" to your f:image.</p>

ContentLicense: CC BY-SA 3.0

Body:
There's an awesome feature in TYPO3 8.7 called cropping variants in image manipulation tool. Details informations can be found in official feature description #75880. Thanks to this we can allow back-end user to crop one image in multiple variants, for exampple: for mobile and desktop. See image below.

Image from: https://techblog.sitegeist.de/responsive-images-with-typo3-8-7/

Configuration can be done in TCA:

'config' => [
 'type' => 'imageManipulation',
 'cropVariants' => [
     'mobile' => [
         'title' => 'LLL:EXT:ext_key/Resources/Private/Language/locallang.xlf:imageManipulation.mobile',
         'allowedAspectRatios' => [
             '4:3' => [
                 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.4_3',
                 'value' => 4 / 3
             ],
             'NaN' => [
                 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.free',
                 'value' => 0.0
             ],
         ],
     ],
     'desktop' => [
         'title' => 'LLL:EXT:ext_key/Resources/Private/Language/locallang.xlf:imageManipulation.desktop',
         'allowedAspectRatios' => [
             '4:3' => [
                 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.4_3',
                 'value' => 4 / 3
             ],
             'NaN' => [
                 'title' => 'LLL:EXT:lang/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.free',
                 'value' => 0.0
             ],
         ],
     ],
 ]

]

I'm trying to integrate it into tx_news. I want to use existing field called fal_media. The configuration of this field you can find in the source file of tx_news in GitHub. Screenshot of the code snippet below:

Somebody have an idea how cropping variants in image manipulation can be implemented in tx_news extension for field fal_media?


问:
Flink Avro 1.8.1 NoSuchMethodError when running on cluster
We run Flink 1.3.0 CEP jobs and rely on Avro 1.8.1 (LogicalType does not exist in Avro 1.7.7) to serialize complex events (as POJOs). It's working when run from within the IDE (IntelliJ), but when we package the jar-file and deploy it to the cluster we get:

```<code>java.lang.NoSuchMethodError: org.apache.avro.Schema.setLogicalType(Lorg/apache/avro/LogicalType;)V
at org.apache.avro.LogicalType.addToSchema(LogicalType.java:72)
</code>```

However, it seems that we build the jar containing the right Avro package version (1.8.1) regarding the build output.

```<code>mvn clean package -Pbuild-jar
...
[INFO] Including org.apache.avro:avro:jar:1.8.1 in the shaded jar.
...
</code>```

Question: How can we assure that our Flink cluster uses the correct Avro version (1.8.1)?

Our pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.group.flink</groupId>
<artifactId>cep</artifactId>
<version>0.2</version>
<packaging>jar</packaging>

<name>Complex Event Processing</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <flink.version>1.3.0</flink.version>
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
    <kafka.version>0.10.2.1</kafka.version>
    <scala.version>2.11</scala.version>
    <avro.version>1.8.1</avro.version>
    <junit.version>5.0.0-M4</junit.version>
</properties>

<repositories>
    <repository>
        <id>apache.snapshots</id>
        <name>Apache Development Snapshot Repository</name>
        <url>https://repository.apache.org/content/repositories/snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

<!--

    Execute "mvn clean package -Pbuild-jar"
    to build a jar file out of this project!

    How to use the Flink Quickstart pom:

    a) Adding new dependencies:
        You can add dependencies to the list below.
        Please check if the maven-shade-plugin below is filtering out your dependency
        and remove the exclude from there.

    b) Build a jar for running on the cluster:
        There are two options for creating a jar from this project

        b.1) "mvn clean package" -> this will create a fat jar which contains all
                dependencies necessary for running the jar created by this pom in a cluster.
                The "maven-shade-plugin" excludes everything that is provided on a running Flink cluster.

        b.2) "mvn clean package -Pbuild-jar" -> This will also create a fat-jar, but with much
                nicer dependency exclusion handling. This approach is preferred and leads to
                much cleaner jar files.
-->

<dependencies>
    <!-- Apache Flink dependencies -->
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-java</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-java_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-clients_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-cep_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-kafka-0.10_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <!-- explicitly add a standard loggin framework, as Flink does not (in the future) have
        a hard dependency on one specific framework by default -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_${scala.version}</artifactId>
        <version>${kafka.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro</artifactId>
        <version>${avro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${junit.version}</version>
    </dependency>
    <dependency>
        <groupId>com.github.smueller18</groupId>
        <artifactId>avro-builder</artifactId>
        <version>0.5</version>
    </dependency>
    <dependency>
        <groupId>com.github.smueller18</groupId>
        <artifactId>flink-serialization</artifactId>
        <version>0.6</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.9.9</version>
    </dependency>

</dependencies>

<profiles>
    <profile>
        <!-- Profile for packaging correct JAR files -->
        <id>build-jar</id>

        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>

        <dependencies>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-java</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-streaming-java_${scala.version}</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-clients_${scala.version}</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <!-- disable the exclusion rules -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.4.1</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <artifactSet>
                                    <excludes combine.self="override"></excludes>
                                </artifactSet>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

<build>
    <plugins>
        <!-- We use the maven-shade plugin to create a fat jar that contains all dependencies
        except flink and it's transitive dependencies. The resulting fat-jar can be executed
        on a cluster. Change the value of Program-Class if your program entry point changes. -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.1</version>
            <executions>
                <!-- Run shade goal on package phase -->
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <artifactSet>
                            <excludes>
                                <!-- This list contains all dependencies of flink-dist
                                Everything else will be packaged into the fat-jar
                                -->
                                <exclude>org.apache.flink:flink-annotations</exclude>
                                <exclude>org.apache.flink:flink-shaded-hadoop2</exclude>
                                <exclude>org.apache.flink:flink-shaded-curator-recipes</exclude>
                                <exclude>org.apache.flink:flink-core</exclude>
                                <exclude>org.apache.flink:flink-java</exclude>
                                <exclude>org.apache.flink:flink-scala_2.11</exclude>
                                <exclude>org.apache.flink:flink-runtime_2.11</exclude>
                                <exclude>org.apache.flink:flink-optimizer_2.11</exclude>
                                <exclude>org.apache.flink:flink-clients_2.11</exclude>
                                <exclude>org.apache.flink:flink-avro_2.11</exclude>
                                <exclude>org.apache.flink:flink-examples-batch_2.11</exclude>
                                <exclude>org.apache.flink:flink-examples-streaming_2.11</exclude>
                                <exclude>org.apache.flink:flink-streaming-java_2.11</exclude>
                                <exclude>org.apache.flink:flink-streaming-scala_2.11</exclude>
                                <exclude>org.apache.flink:flink-scala-shell_2.11</exclude>
                                <exclude>org.apache.flink:flink-python</exclude>
                                <exclude>org.apache.flink:flink-metrics-core</exclude>
                                <exclude>org.apache.flink:flink-metrics-jmx</exclude>
                                <exclude>org.apache.flink:flink-statebackend-rocksdb_2.11</exclude>

                                <!-- Also exclude very big transitive dependencies of Flink

                                WARNING: You have to remove these excludes if your code relies on other
                                versions of these dependencies.

                                -->

                                <exclude>log4j:log4j</exclude>
                                <exclude>org.scala-lang:scala-library</exclude>
                                <exclude>org.scala-lang:scala-compiler</exclude>
                                <exclude>org.scala-lang:scala-reflect</exclude>
                                <exclude>com.data-artisans:flakka-actor_*</exclude>
                                <exclude>com.data-artisans:flakka-remote_*</exclude>
                                <exclude>com.data-artisans:flakka-slf4j_*</exclude>
                                <exclude>io.netty:netty-all</exclude>
                                <exclude>io.netty:netty</exclude>
                                <exclude>commons-fileupload:commons-fileupload</exclude>
                                <!--<exclude>org.apache.avro:avro</exclude>-->
                                <exclude>commons-collections:commons-collections</exclude>
                                <exclude>org.codehaus.jackson:jackson-core-asl</exclude>
                                <exclude>org.codehaus.jackson:jackson-mapper-asl</exclude>
                                <exclude>com.thoughtworks.paranamer:paranamer</exclude>
                                <exclude>org.xerial.snappy:snappy-java</exclude>
                                <exclude>org.apache.commons:commons-compress</exclude>
                                <exclude>org.tukaani:xz</exclude>
                                <exclude>com.esotericsoftware.kryo:kryo</exclude>
                                <exclude>com.esotericsoftware.minlog:minlog</exclude>
                                <exclude>org.objenesis:objenesis</exclude>
                                <exclude>com.twitter:chill_*</exclude>
                                <exclude>com.twitter:chill-java</exclude>
                                <exclude>commons-lang:commons-lang</exclude>
                                <exclude>junit:junit</exclude>
                                <exclude>org.apache.commons:commons-lang3</exclude>
                                <exclude>org.slf4j:slf4j-api</exclude>
                                <exclude>org.slf4j:slf4j-log4j12</exclude>
                                <exclude>log4j:log4j</exclude>
                                <exclude>org.apache.commons:commons-math</exclude>
                                <exclude>org.apache.sling:org.apache.sling.commons.json</exclude>
                                <exclude>commons-logging:commons-logging</exclude>
                                <exclude>commons-codec:commons-codec</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-core</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-databind</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-annotations</exclude>
                                <exclude>stax:stax-api</exclude>
                                <exclude>com.typesafe:config</exclude>
                                <exclude>org.uncommons.maths:uncommons-maths</exclude>
                                <exclude>com.github.scopt:scopt_*</exclude>
                                <exclude>commons-io:commons-io</exclude>
                                <exclude>commons-cli:commons-cli</exclude>
                            </excludes>
                        </artifactSet>
                        <filters>
                            <filter>
                                <artifact>org.apache.flink:*</artifact>
                                <excludes>
                                    <!-- exclude shaded google but include shaded curator -->
                                    <exclude>org/apache/flink/shaded/com/**</exclude>
                                    <exclude>web-docs/**</exclude>
                                </excludes>
                            </filter>
                            <filter>
                                <!-- Do not copy the signatures in the META-INF folder.
                                Otherwise, this might cause SecurityExceptions when using the JAR. -->
                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>
                        <!-- If you want to use ./bin/flink run <quickstart jar> uncomment the following lines.
                        This will add a Main-Class entry to the manifest file -->
                        <!--
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>de.hska.stcs.cep.StreamingJob</mainClass>
                            </transformer>
                        </transformers>
                        -->
                        <createDependencyReducedPom>false</createDependencyReducedPom>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source> <!-- If you want to use Java 8, change this to "1.8" -->
                <target>1.8</target> <!-- If you want to use Java 8, change this to "1.8" -->
            </configuration>
        </plugin>
    </plugins>

    <!-- If you want to use Java 8 Lambda Expressions uncomment the following lines -->
    <!--
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>jdt</compilerId>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.eclipse.tycho</groupId>
                        <artifactId>tycho-compiler-jdt</artifactId>
                        <version>0.21.0</version>
                    </dependency>
                </dependencies>
            </plugin>

            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-assembly-plugin</artifactId>
                                    <versionRange>[2.4,)</versionRange>
                                    <goals>
                                        <goal>single</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore/>
                                </action>
                            </pluginExecution>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-compiler-plugin</artifactId>
                                    <versionRange>[3.1,)</versionRange>
                                    <goals>
                                        <goal>testCompile</goal>
                                        <goal>compile</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore/>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
    -->
</build>
</code>```

UPDATE: I build flink 1.3 from source and updated the avro version (from 1.7.7 to 1.8.1) in the project's pom.xml and it seems to work for now. Still unsure why it's not working when building the fat jar.

答: Please try putting the avro jar in the /lib folder.</p>

Body:
We run Flink 1.3.0 CEP jobs and rely on Avro 1.8.1 (LogicalType does not exist in Avro 1.7.7) to serialize complex events (as POJOs). It's working when run from within the IDE (IntelliJ), but when we package the jar-file and deploy it to the cluster we get:

java.lang.NoSuchMethodError: org.apache.avro.Schema.setLogicalType(Lorg/apache/avro/LogicalType;)V
at org.apache.avro.LogicalType.addToSchema(LogicalType.java:72)

However, it seems that we build the jar containing the right Avro package version (1.8.1) regarding the build output.

mvn clean package -Pbuild-jar
...
[INFO] Including org.apache.avro:avro:jar:1.8.1 in the shaded jar.
...

Question: How can we assure that our Flink cluster uses the correct Avro version (1.8.1)?

Our pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.group.flink</groupId>
<artifactId>cep</artifactId>
<version>0.2</version>
<packaging>jar</packaging>

<name>Complex Event Processing</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <flink.version>1.3.0</flink.version>
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
    <kafka.version>0.10.2.1</kafka.version>
    <scala.version>2.11</scala.version>
    <avro.version>1.8.1</avro.version>
    <junit.version>5.0.0-M4</junit.version>
</properties>

<repositories>
    <repository>
        <id>apache.snapshots</id>
        <name>Apache Development Snapshot Repository</name>
        <url>https://repository.apache.org/content/repositories/snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

<dependencies>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-java</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-java_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-clients_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-cep_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-kafka-0.10_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_${scala.version}</artifactId>
        <version>${kafka.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro</artifactId>
        <version>${avro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${junit.version}</version>
    </dependency>
    <dependency>
        <groupId>com.github.smueller18</groupId>
        <artifactId>avro-builder</artifactId>
        <version>0.5</version>
    </dependency>
    <dependency>
        <groupId>com.github.smueller18</groupId>
        <artifactId>flink-serialization</artifactId>
        <version>0.6</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.9.9</version>
    </dependency>

</dependencies>

<profiles>
    <profile>

        <id>build-jar</id>

        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>

        <dependencies>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-java</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-streaming-java_${scala.version}</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-clients_${scala.version}</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>

        <build>
            <plugins>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.4.1</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <artifactSet>
                                    <excludes combine.self="override"></excludes>
                                </artifactSet>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

<build>
    <plugins>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.1</version>
            <executions>

                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <artifactSet>
                            <excludes>

                                <exclude>org.apache.flink:flink-annotations</exclude>
                                <exclude>org.apache.flink:flink-shaded-hadoop2</exclude>
                                <exclude>org.apache.flink:flink-shaded-curator-recipes</exclude>
                                <exclude>org.apache.flink:flink-core</exclude>
                                <exclude>org.apache.flink:flink-java</exclude>
                                <exclude>org.apache.flink:flink-scala_2.11</exclude>
                                <exclude>org.apache.flink:flink-runtime_2.11</exclude>
                                <exclude>org.apache.flink:flink-optimizer_2.11</exclude>
                                <exclude>org.apache.flink:flink-clients_2.11</exclude>
                                <exclude>org.apache.flink:flink-avro_2.11</exclude>
                                <exclude>org.apache.flink:flink-examples-batch_2.11</exclude>
                                <exclude>org.apache.flink:flink-examples-streaming_2.11</exclude>
                                <exclude>org.apache.flink:flink-streaming-java_2.11</exclude>
                                <exclude>org.apache.flink:flink-streaming-scala_2.11</exclude>
                                <exclude>org.apache.flink:flink-scala-shell_2.11</exclude>
                                <exclude>org.apache.flink:flink-python</exclude>
                                <exclude>org.apache.flink:flink-metrics-core</exclude>
                                <exclude>org.apache.flink:flink-metrics-jmx</exclude>
                                <exclude>org.apache.flink:flink-statebackend-rocksdb_2.11</exclude>

                                <exclude>log4j:log4j</exclude>
                                <exclude>org.scala-lang:scala-library</exclude>
                                <exclude>org.scala-lang:scala-compiler</exclude>
                                <exclude>org.scala-lang:scala-reflect</exclude>
                                <exclude>com.data-artisans:flakka-actor_*</exclude>
                                <exclude>com.data-artisans:flakka-remote_*</exclude>
                                <exclude>com.data-artisans:flakka-slf4j_*</exclude>
                                <exclude>io.netty:netty-all</exclude>
                                <exclude>io.netty:netty</exclude>
                                <exclude>commons-fileupload:commons-fileupload</exclude>

                                <exclude>commons-collections:commons-collections</exclude>
                                <exclude>org.codehaus.jackson:jackson-core-asl</exclude>
                                <exclude>org.codehaus.jackson:jackson-mapper-asl</exclude>
                                <exclude>com.thoughtworks.paranamer:paranamer</exclude>
                                <exclude>org.xerial.snappy:snappy-java</exclude>
                                <exclude>org.apache.commons:commons-compress</exclude>
                                <exclude>org.tukaani:xz</exclude>
                                <exclude>com.esotericsoftware.kryo:kryo</exclude>
                                <exclude>com.esotericsoftware.minlog:minlog</exclude>
                                <exclude>org.objenesis:objenesis</exclude>
                                <exclude>com.twitter:chill_*</exclude>
                                <exclude>com.twitter:chill-java</exclude>
                                <exclude>commons-lang:commons-lang</exclude>
                                <exclude>junit:junit</exclude>
                                <exclude>org.apache.commons:commons-lang3</exclude>
                                <exclude>org.slf4j:slf4j-api</exclude>
                                <exclude>org.slf4j:slf4j-log4j12</exclude>
                                <exclude>log4j:log4j</exclude>
                                <exclude>org.apache.commons:commons-math</exclude>
                                <exclude>org.apache.sling:org.apache.sling.commons.json</exclude>
                                <exclude>commons-logging:commons-logging</exclude>
                                <exclude>commons-codec:commons-codec</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-core</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-databind</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-annotations</exclude>
                                <exclude>stax:stax-api</exclude>
                                <exclude>com.typesafe:config</exclude>
                                <exclude>org.uncommons.maths:uncommons-maths</exclude>
                                <exclude>com.github.scopt:scopt_*</exclude>
                                <exclude>commons-io:commons-io</exclude>
                                <exclude>commons-cli:commons-cli</exclude>
                            </excludes>
                        </artifactSet>
                        <filters>
                            <filter>
                                <artifact>org.apache.flink:*</artifact>
                                <excludes>

                                    <exclude>org/apache/flink/shaded/com/**</exclude>
                                    <exclude>web-docs/**</exclude>
                                </excludes>
                            </filter>
                            <filter>

                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>

                        <createDependencyReducedPom>false</createDependencyReducedPom>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>

</build>

UPDATE: I build flink 1.3 from source and updated the avro version (from 1.7.7 to 1.8.1) in the project's pom.xml and it seems to work for now. Still unsure why it's not working when building the fat jar.


问:
React native fresh install ReferenceError: Unknown plugin "transform-runtime" specified

update

This worked for me per @digit comment

```<code>"dependencies": {
        "react": "16.0.0-alpha.12",
    "react-native": "0.45.1"
},
"devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "2.0.0",
    ...
},
</code>```

I followed the instructions for building projects in native code for macos > ios. I ran react-native run-ios and I got the error in the title... Any thoughts? My thoughts are at the end if you want to read it.

```<code>Unknown plugin "transform-runtime" specified in "<myprojectdir>/node_modules/regenerator-transform/package.json" at 0, attempted to resolve relative to "<myprojectdir>/node_modules/regenerator-transform" (While processing preset: "<myprojectdir>/node_modules/babel-preset-react-native/index.js")
</code>```

package.json

```<code> "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.0.0-alpha.12",
    "react-native": "0.46.0"
  },
  "devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "2.1.0",
    "jest": "20.0.4",
    "react-test-renderer": "16.0.0-alpha.12"
  },
  "jest": {
    "preset": "react-native"
  }
</code>```

my npm & node versions

```<code>➜  nativeapp npm -v
4.6.1
➜  nativeapp node -v
v8.1.3
</code>```

Thank you for looking. Below is my unrelated ranting about my react native but I do genuinely seek some guidance if you have any.

I watched the lectures of coders who works on react-native and I read as much as I can prior to my project and from what I can tell they are all geniuses. I am not being sarcastic I sincerely think that. Yet I fail to understand why my experience with react native is so bad. I mean ... fresh install ... should work? I do not know how many expo projects I have created and moved my stuff around before this because every freakin time I installed a package from npm, everything broke.

I've been a full time coder for 8 years and I've worked projects using things from bash to perl to python to php to golang to mysql to mongo to jquery to angular to vue to vanillajs to ionic to java to C to R yet I do not think I have ever been this frustrated with any new stack I have ever worked on.

What am I missing? What is it that I am doing wrong? Please somebody tell me because I am about to lose my mind and throw my laptop out the window. I spend my time debugging errors instead of making progress in my project. I get up in the morning two hours before work to work on this project and I work on it at home after work... It is 8PM and I've been trying to run the app for two hours now.

I am beginning to think I am the only one with these problems thus I am the cause. I see all these companies using react native and it does not make sense for any company to invest in something that is going to make its developers have the same experience as me. Just spending time on getting it to open.

Sorry about my ranting and please note that I care more about fixing the issue.

I am just passionate about what I do and I do not like spending my hours and not making progress for reasons that I do not expect to have. Thx for looking

答:
According to this link https://github.com/facebook/react-native/issues/14843,
this is a bugs related to the babel-preset-react-native for react native v0.46. For temporary solution

1) Remove .babelrc by doing rm -rf .babelrc inside root folder

2) Revert babel-preset-react-native to the version 2.0.0

Body:
update

This worked for me per @digit comment

"dependencies": {
        "react": "16.0.0-alpha.12",
    "react-native": "0.45.1"
},
"devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "2.0.0",
    ...
},

I followed the instructions for building projects in native code for macos > ios. I ran react-native run-ios and I got the error in the title... Any thoughts? My thoughts are at the end if you want to read it.

Unknown plugin "transform-runtime" specified in "<myprojectdir>/node_modules/regenerator-transform/package.json" at 0, attempted to resolve relative to "<myprojectdir>/node_modules/regenerator-transform" (While processing preset: "<myprojectdir>/node_modules/babel-preset-react-native/index.js")

package.json

 "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.0.0-alpha.12",
    "react-native": "0.46.0"
  },
  "devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "2.1.0",
    "jest": "20.0.4",
    "react-test-renderer": "16.0.0-alpha.12"
  },
  "jest": {
    "preset": "react-native"
  }

my npm & node versions

➜  nativeapp npm -v
4.6.1
➜  nativeapp node -v
v8.1.3

Thank you for looking. Below is my unrelated ranting about my react native but I do genuinely seek some guidance if you have any.

I watched the lectures of coders who works on react-native and I read as much as I can prior to my project and from what I can tell they are all geniuses. I am not being sarcastic I sincerely think that. Yet I fail to understand why my experience with react native is so bad. I mean ... fresh install ... should work? I do not know how many expo projects I have created and moved my stuff around before this because every freakin time I installed a package from npm, everything broke.

I've been a full time coder for 8 years and I've worked projects using things from bash to perl to python to php to golang to mysql to mongo to jquery to angular to vue to vanillajs to ionic to java to C to R yet I do not think I have ever been this frustrated with any new stack I have ever worked on.

What am I missing? What is it that I am doing wrong? Please somebody tell me because I am about to lose my mind and throw my laptop out the window. I spend my time debugging errors instead of making progress in my project. I get up in the morning two hours before work to work on this project and I work on it at home after work... It is 8PM and I've been trying to run the app for two hours now.

I am beginning to think I am the only one with these problems thus I am the cause. I see all these companies using react native and it does not make sense for any company to invest in something that is going to make its developers have the same experience as me. Just spending time on getting it to open.

Sorry about my ranting and please note that I care more about fixing the issue.

I am just passionate about what I do and I do not like spending my hours and not making progress for reasons that I do not expect to have. Thx for looking


问:
Javascript closure vs regular function
I was reading an expemple of javascript closure. And there is one thing I don't understand.

Here is the exemple:

```<code>function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
</code>```

Here is the full exemple: Fidle Exemple

What I understand, Is when you click on the element size-12 for ex, you will execute the anonymous function which change the size to 12.

What I don't understand, is if you change the code this way:

```<code>function makeSizer(size) {

    document.body.style.fontSize = size + 'px';

}
</code>```

and call makeSizer(12) instead of size12 on click event, it doesn't work.

Ok I get this is what make closure interesting, but why my modification does not work ?

Regard,
Charles.

答:
The onclick property expects a function to be passed. In your second example that is not the case as makeSizer(12) is not a function, but a function call. To get it to work you would need to wrap it inside an anonymous function like:

```<code>document.getElementById('size-12').onclick = function() {makeSizer(12);};
</code>```

Title: Javascript closure vs regular function

Body:
I was reading an expemple of javascript closure. And there is one thing I don't understand.

Here is the exemple:

function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

Here is the full exemple: Fidle Exemple

What I understand, Is when you click on the element size-12 for ex, you will execute the anonymous function which change the size to 12.

What I don't understand, is if you change the code this way:

function makeSizer(size) {

    document.body.style.fontSize = size + 'px';

}

and call makeSizer(12) instead of size12 on click event, it doesn't work.

Ok I get this is what make closure interesting, but why my modification does not work ?

Regard,
Charles.

Body:
The onclick property expects a function to be passed. In your second example that is not the case as makeSizer(12) is not a function, but a function call. To get it to work you would need to wrap it inside an anonymous function like:

document.getElementById('size-12').onclick = function() {makeSizer(12);};