How to select multiple images from android gallery separately - android

What I want to accomplish is to select a sperate image whenever I click on a separate Imageview. For example, If a click on ImageView_1 I can select one image from the gallery and if I click on Imagview_2 I can select a separate image from the gallery. I have seen there are already many answers to this question but they are all different from what is I want to do. In the previous answers, they get all the images as a list in OnActivity Results and all the images are selected at once from the gallery.
My code
Dependency Used
implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
private void ImageOnclick(){
image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(Upload_New_Product.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
openFileChooser();
} else {
requestStoragePermission();
}
}
});
image_profile2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(Upload_New_Product.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
openFileChooser2();
} else {
requestStoragePermission();
}
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
private void openFileChooser2() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST2);
}
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
ImageUri = data.getData();
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
// .setAspectRatio(1, 1)
.start(this);
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
resultUri = result.getUri();
if (Build.VERSION.SDK_INT >= 29) {
try {
bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(), resultUri));
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Use older version
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
}
//setImage_profile();
resized = Bitmap.createScaledBitmap(bitmap, 600, 600, true);
image_profile.setImageBitmap(resized);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
// UploadingImage();
// UploadingThumbnailImage();
if (requestCode == PICK_IMAGE_REQUEST2 && resultCode == RESULT_OK && data != null) {
ImageUri2 = data.getData();
CropImage.activity(ImageUri2)
.setGuidelines(CropImageView.Guidelines.ON)
// .setAspectRatio(1, 1)
.start(this);
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
resultUri2 = result.getUri();
if (Build.VERSION.SDK_INT >= 29) {
try {
bitmap2 = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(), resultUri2));
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Use older version
try {
bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri2);
} catch (IOException e) {
e.printStackTrace();
}
}
resized2 = Bitmap.createScaledBitmap(bitmap2, 600, 600, true);
image_profile2.setImageBitmap(resized2);
//setImage_profile2();
// UploadingImage();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}

You missed this line:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
And activity result should be like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST) {
if(resultCode == Activity.RESULT_OK) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for(int i = 0; i < count; i++)
Uri imageUri = data.getClipData().getItemAt(i).getUri();
//TODO: do something; here is your selected images
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//TODO: do something
}
}
}
Intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select images"), PICK_IMAGE_REQUEST);

Related

onbackpressed in show file chooser

private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
hey. i used that code for pick image from storage. but if i press the back button in my gadget. he is fc . how to give condition on canceled pick from storage..and not force close?
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST) {
filePath = data.getData();
if(filePath != null) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, data.getDataString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}else if(filePath == null){
startActivity(new Intent(this,HalamanUser.class));
}
} else if (requestCode == CAMERA_REQUEST) {
Log.i("hello", "REQUEST cALL");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Log.i("hello", "Exception" + e.getMessage());
}
}else {
startActivity(new Intent(this,HalamanUser.class));
}
}
When the user presses back, the result is RESULT_CANCELED, and the data that you receive is null. So the app crashes when you call data.getData(), as you are calling getData() on a null object. The are a few ways to get around this: you can check what the resultCode is, and make sure it's RESULT_OK. You can also simply check whether the data Intent is null before trying to get the data from it:
if (requestCode == PICK_IMAGE_REQUEST) {
if (data != null) {
filePath = data.getData();
} else {
// Note: if filePath is by default null, you don't need this else statement
filePath = null;
}
if (filePath != null) {
...

onActivityResult : android.net.Uri android.content.Intent.getData()' on a null object reference

Its work perfectly when i click image from the camera or back press from camera.
Ii also works perfectly when i select an image from the gallery but it occurs error when i back press from the gallery without selecting any image at this line filePath = data.getData();.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.net.Uri android.content.Intent.getData()' on a null
object reference
private void changeProfileImage() {
try {
PackageManager pm = getPackageManager();
int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
if (hasPerm == PackageManager.PERMISSION_GRANTED) {
final CharSequence[] options = {"Take Photo", "Choose From Gallery", "Cancel"};
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(AddProduct.this);
builder.setTitle("Select Option");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
dialog.dismiss();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, PICK_IMAGE_CAMERA);
} else if (options[item].equals("Choose From Gallery")) {
dialog.dismiss();
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
} else Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_CAMERA) {
try {
bitmap = (Bitmap) data.getExtras().get("data");
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_GALLERY) {
try {
filePath = data.getData();
if (filePath != null) {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Yes, If you not selected any Image and simply come back from the Gallery , It will return null in the Intent Data. Check data!=null before taking getData()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_CAMERA) {
try {
bitmap = (Bitmap) data.getExtras().get("data");
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_GALLERY) {
try {
if(data!=null)
{ // user selects some Image
filePath = data.getData();
if (filePath != null) {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
}
}
else
{ // user simply backpressed from gallery
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

CropActivity is not starting in onActivityResult inside Fragment

I am calling an intent to select an image and later to crop the image into aspect ratio(1,1), but when i run the app the gallery is opening but when i select the image it closes and gets back to the Fragment.
Below is the code of my Button's on click listener
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent,
"SELECT IMAGE"), GALLERY_PICK);
}
});
this is the code for onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.setMinCropWindowSize(500, 500)
.start(getActivity());
Toast.makeText(SettingsActivity.this, imageUri,
Toast.LENGTH_LONG).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
Exception error = result.getError();
}
}
}
Crop activity is not starting and the app goes back to the fragment screen when i select the pic
Below is the code of MainActivity where i have used bottom navigation view and used OnActivity result as well
private void showPlacePicker() {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (Exception e) {
Log.e(TAG, e.getStackTrace().toString());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
----code---
}
}
I have used this library in one of my projects and in that I didn't explicitly create a image picker but instead let the library handle it for me. To do this,
in your code
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity()
.setAspectRatio(1, 1)
.setMinCropWindowSize(500, 500)
.start(getContext());
}
});
Handle the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri imageUri = result.getUri();
//handle the image
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
//handle error
} else if(resultCode == RESULT_CANCELED){
//handle cancel case
}
}
}
For more information
In case of using appcompact fragment we cannot use .start(getActivity()) to start the crop activity.
Instead of this use:
.start(getContext(), this)
Here is code look like in fragments:
CropImage.activity(uri).setGuidelines(CropImageView.Guidelines.ON).start(getContext(), this);
ActivityResult is more suitable :
#Override
public void onActivityResult(ActivityResult activityResult) {
if (activityResult.getResultCode() == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(activityResult.getData());
}
if (activityResult.getResultCode() == RESULT_OK) {
Uri resultUri = result.getUri();
} else if (activityResult.getResultCode() == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}

Don't understand why I am not getting my Image?

I am working on an demo application where I am taking picture then save it.
I want to display picture inside Image view . I don't understand why it is not working . I recently tried out some solution but non of them worked for me .
Is there anyone who can tell me what's wrong with my code .
// This is my code
private Button takePictureButton;
private ImageView imageView;
private Uri file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageview);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED&&grantResults[2]==PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
//Code that bind image with ImageView
if (resultCode == RESULT_OK) {
imageView.setMaxHeight(100);
imageView.setMaxWidth(100);
imageView.setImageURI(null);
imageView.setImageURI(file);
}
}
//Thanks in advance
I dont really understand what are you doing at here. But :
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
imageView.setMaxHeight(100);
imageView.setMaxWidth(100);
imageView.setImageURI(uri);
}
Replace this code on your activityResult, it is working for me.
Try this way it will work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
For more See this http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample
In My case it worked for me:
private static Bitmap Image = null;
private static Bitmap rotateImage = null;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("resultCode", Integer.toString(resultCode));
Log.e("requestCode", Integer.toString(requestCode));
Log.e("Inside If","Success");
Uri mImageUri = data.getData();
try {
Image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
if (getOrientation(getApplicationContext(), mImageUri) != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
if (rotateImage != null)
rotateImage.recycle();
rotateImage = Bitmap.createBitmap(Image, 0, 0, Image.getWidth(), Image.getHeight(), matrix,true);
imageView.setImageBitmap(rotateImage);
//saveImagetoFolder(rotateImage);
} else {
imageView.setImageBitmap(Image);
// saveImagetoFolder(Image);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Fragment getting closed after on activity result call

I have a fragments A and B. A contains a list and B has an imageview. when i click on a list item in fragment A it goes to B. I'm calling camera and gallery intent from B.
In B
alert.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, PICK_FROM_CAMERA);
} else if (item == 1) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, PICK_FROM_FILE);
} else {
dialog.cancel();
}
}
});
onActivityResult in B
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_CAMERA) {
if (resultCode == getActivity().RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
cameraIcon.setImageBitmap(bitmap);
} else if (resultCode == getActivity().RESULT_CANCELED) {
Toast.makeText(getActivity(), "Result has been cancelled!",
Toast.LENGTH_LONG).show();
}
} else if (requestCode == PICK_FROM_FILE) {
try {
if (resultCode == getActivity().RESULT_OK) {
try {
stream = getActivity().getContentResolver()
.openInputStream(data.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap = BitmapFactory.decodeStream(stream);
cameraIcon
.setImageBitmap(Bitmap.createScaledBitmap(bitmap,
bitmap.getWidth() / 2,
bitmap.getHeight() / 2, true));
} else if (resultCode == getActivity().RESULT_CANCELED) {
Toast.makeText(getActivity(), "Result has been cancelled!",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
}
But some times after the intent collects the image and comes to onActivityResult fragment B
get closed and goes to fragment A instead of setting the image to the image view in fragment B.....
What am i doing wrong please help
Please check using another device.I think the device issue.
Just a guess, but I would say an exception is being thrown in fragment B after onActivityResult has finished.. perhaps you should check your event log/trace the events in the onResume/createView etc.

Categories

Resources