onbackpressed in show file chooser - android

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) {
...

Related

How to select multiple images from android gallery separately

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);

Attempting to implement a feature where a user can use their phone camera to take a picture and then it will be uploaded as their profile pic

I'm currently running into an issue with implementing a feature on my app where a user can take a picture using their phone's camera and then have it display as a bitmap image as well as be uploaded to Firebase.
I've seen several similar questions answered on here but nothing seems to be working for me, so I was hoping if someone could give my code a look and have insight for what I might be doing incorrectly.
My general process as of right now is that my "Choose from Gallery" option is working, but my "Take Photo" is not. When clicked in selectProfilePicOption(), I am able to take a picture and confirm it, but the data sent to onActivityResult() continues to get null. I want to be able to pass the taken photo and upload it as a Bitmap to my uploadImageToFirebase() function.
Thanks to all in advance for any assistance!
Here's my current code:
private void selectProfilePicOption(Context context){
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(options[which].equals("Take Photo")){
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, TAKE_IMAGE_REQUEST);
}else if(options[which].equals("Choose from Gallery")){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select image..."), PICK_IMAGE_REQUEST);
}else if(options[which].equals("Cancel")){
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case TAKE_IMAGE_REQUEST:
if(resultCode == RESULT_OK){
data.getExtras().get("data");
File file = new File(Environment.getExternalStorageDirectory().getPath());
Uri uri = Uri.fromFile(file);
try{
System.out.println("attempting to store bitmap");
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
uploadImageToFirebase(bitmap);
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
break;
case PICK_IMAGE_REQUEST:
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
uploadImageToFirebase(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}
private void uploadImageToFirebase(final Bitmap bitmap){
if(filePath != null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = mStorageRef.child("images/ProfilePics/" + mUser.getUid());
ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
profilePicture.setImageBitmap(bitmap);
Toast.makeText(SetProfileData.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(SetProfileData.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int)progress + "%");
}
});
}
}
The line data.getExtras().get("data"); contains the thumbnail of your captured image, but for some reasons, you are completely ignoring it.
Do it this way,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case TAKE_IMAGE_REQUEST:
if(resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap) intent.getExtras().get("data") //this line is important
uploadImageToFirebase(bitmap);
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
break;
case PICK_IMAGE_REQUEST:
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
uploadImageToFirebase(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
But beware the image thumbnail you received on onActivityResult() and uploaded to FireBase is not the full resolution image but just a compressed version of it. In order to get the full-size image, you can check out this

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();
}
}
}

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.

How to upload image from gallery in android

I want to upload image from my phone gallery into my application .In my application there is button named upload. when i click button,it should move to gallery and in gallery if i select image that selected image should display as thumbnail in application.I want to upload 10 images, from gallery in my application.
On click of the gallery button, start startActivityForResult as follows:
startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
Consequently, detect GET_FROM_GALLERY (which is a static int, any request number of your choice e.g., public static final int GET_FROM_GALLERY = 3;) inside onActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Detects request codes
if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
To view gallery:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),REQUEST_CODE);
and to use it in your app:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
switch (requestCode) {
case REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
//data gives you the image uri. Try to convert that to bitmap
break;
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e(TAG, "Selecting picture cancelled");
}
break;
}
} catch (Exception e) {
Log.e(TAG, "Exception in onActivityResult : " + e.getMessage());
}
}
This is the way to go:
startActivityForResult(
new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
),
GET_FROM_GALLERY
);

Categories

Resources