Skip to content

Instantly share code, notes, and snippets.

@arthtilva
Last active May 18, 2019 17:17
Show Gist options
  • Save arthtilva/b5acb972316febf047777336c1e6efe1 to your computer and use it in GitHub Desktop.
Save arthtilva/b5acb972316febf047777336c1e6efe1 to your computer and use it in GitHub Desktop.
Choose Image and other media from gallery or camera
Uri ImagefileUri;
int hasStoragePermission, hasCameraPermission, GALLERY_CLICK = 100, CAMERA_CLICK = 101;
File appImageFolder;
boolean askOnceAgain = false;
hasStoragePermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
11);
} else {
//onCreate
appImageFolder = new File(Environment.getExternalStorageDirectory(), "/" + getResources().getString(R.string.app_name) + "/images/profile.png");
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[]{"Gallery", "Camera"},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
//Gallery
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Select File"), GALLERY_CLICK);
break;
case 1:
//Camera
hasCameraPermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA},
12);
} else {
ImagefileUri = Uri.fromFile(appImageFolder);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(cameraIntent, CAMERA_CLICK);
}
break;
default:
break;
}
}
}).show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY_CLICK) {
if (null == data) {
Log.i("data", "null");
return;
}
String selectedImagePath;
Uri selectedImageUri = data.getData();
//MEDIA GALLERY
if (selectedImageUri == null)
Log.i("Image File Path", "null");
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
Log.i("Image File Path", "" + selectedImagePath);
} else if (requestCode == CAMERA_CLICK) {
String selectedImagePath;
//MEDIA GALLERY
if (ImagefileUri == null)
Log.i("Image File Path", "null");
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), ImagefileUri);
Log.i("Image File Path", "" + selectedImagePath);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment