Pick & save image from gallery to my app data folder - ANDROID - java

In the below code I'm picking an image from gallery:
Intent choosePicture = new Intent();
choosePicture.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
choosePicture.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
else {
choosePicture.setAction(Intent.ACTION_GET_CONTENT);
}
startActivityForResult(choosePicture, 1);
And in onActivityResults(..):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Context context = getContext();
Activity activity = getActivity();
View view = getView();
if (context == null || activity == null || view == null) {return;}
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Bitmap mImageBitmap = null;
try {
imageUri = Uri.fromFile(new File(currentPhotoPath));
mImageBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(),
imageUri);
} catch (IOException e) {
e.printStackTrace();
}
ImageButton imageButton = view.findViewById(R.id.imgBtn_photo);
if (mImageBitmap != null) {
imageButton.setImageBitmap(scaleBitmap(mImageBitmap));
}
}
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
ImageButton ib = view.findViewById(R.id.imgBtn_photo);
imageUri = data.getData();
Bitmap bitmapImage;
try {
bitmapImage = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), imageUri);
if (bitmapImage.getHeight() > 1000) {
ib.setImageBitmap(scaleBitmap(bitmapImage));
} else {
ib.setImageBitmap(bitmapImage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}
And this is working.
The problem is that if the user delete the photo from his gallery, the app will crash.
How can I store the image to android/data/packagename and get that path, to store it in the DB?
Thanks!

Related

Android / Java WebView Fileupload fails in Android version 10 and 11

I have an android app in which i have a webview. This webview contains a File upload for uploading a picture which does work like a charm from Android 6 to 9. For version 10 it does still work if i use a picture from the gallery but if i try to use one directly through the camera it tells me that it doesn't have permission to the ExternalStorage. I have given it the access in the Settings since i haven't implemented the permission question. For Version 11 it's almost the same except i get no error at all. I have checked some things i think its because the Intent for "ACTION_IMAGE_CAPTURE" returns null for some reason. Did i miss something?
onShowFileChooser
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
Log.d("test", "Test1");
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(getApplicationContext(), "\"Unable to create Image File", Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
createImageFile() -> gives me error "Permission denied" even after giving it the Permissin in Settings
private File createImageFile() throws IOException {
try {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
} catch (Exception e) {
Log.d("test", e.getMessage());
return null;
}
}
onActivityResult()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getDataString() == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
Thanks in advance :D

pick two images separately in Android

I'm making and android app where I need two upload images and save them to server.
When I select it from the first button, it is appeared in the second but I need two different images.
photoUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
photoUpload2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
}
private void chooseImage() {
Intent openGalleryIntent = new Intent();
openGalleryIntent.setType("image/*");
openGalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(openGalleryIntent, "Select Picture"), GALLERY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView.setImageBitmap(bitmap);
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are getting this because you are setting selected image to imageview 1 and 2. to solve this you can use different request codes or use Boolean variable to differentiate the uploading of image 1 and 2
Define two Boolean variable to differentiate the uploading of image 1 and 2
Boolean first = false, second = false;
#Override
public void onClick(View v) {
first = true;
chooseImage();
}
});
photoUpload2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
second = true;
chooseImage();
}
});
}
private void chooseImage() {
Intent openGalleryIntent = new Intent();
openGalleryIntent.setType("image/*");
openGalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(openGalleryIntent, "Select Picture"), GALLERY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
if(first)
{
imageView.setImageBitmap(bitmap);
first = false;
}else if(second)
{
imageView2.setImageBitmap(bitmap);
second = false;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use library to select multiple images from Gallery. There are many libraries that are available, one such is https://github.com/ParkSangGwon/TedPicker
Hope this will help you!
Happy Coding
You are setting same image to both ImageViews.
Change Your Code to
photoUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage(GALLERY_REQUEST_CODE_1);
}
});
photoUpload2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage(GALLERY_REQUEST_CODE_2);
}
});
}
private void chooseImage(int requestCode) {
Intent openGalleryIntent = new Intent();
openGalleryIntent.setType("image/*");
openGalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(openGalleryIntent, "Select Picture"), requestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE_1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == GALLERY_REQUEST_CODE_2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think you have to set same bitmap in both imageView
You should try bellow code
boolean isFromFirstBtn;
photoUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFromFirstBtn = true;
chooseImage();
}
});
photoUpload2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFromFirstBtn = false;
chooseImage();
}
});
}
private void chooseImage() {
Intent openGalleryIntent = new Intent();
openGalleryIntent.setType("image/*");
openGalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(openGalleryIntent, "Select Picture"), GALLERY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
if(isFromFirstBtn){
imageView.setImageBitmap(bitmap);
}else{
imageView2.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to resolve orphan case?

I have used the OnActivity Result code in which I have used switch statement but I got an error in case 2
switch (requestCode) {
case (1):
//Code for camera
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
break;
case (2):
//Code for Gallery
if (resultCode == RESULT_OK) {
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
//imageView.setImageBitmap(photo);
}
You can't have case inside if
switch (requestCode) {
case (1):
//Code for camera
if (requestCode == Activity.CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
}
break;
case (2):
if (resultCode == Activity.RESULT_OK) {
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}

Multiple selected file in webview shows no file chosen

I want to upload multiple images in webview and i can select many file but when i chose file and tap open Webpage Input show no file.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
if(Build.VERSION.SDK_INT >= 21){
Uri[] results = null;
//Check if response is positive
if(resultCode== Activity.RESULT_OK){
if(requestCode == FCR){
if(null == mUMA){
return;
}
if(intent == null){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
}else{
if(requestCode == FCR){
if(null == mUM) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUM.onReceiveValue(result);
mUM = null;
}
}
}
and my onShowFileChooser code is
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams){
if(mUMA != null){
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
startActivityForResult(chooserIntent, FCR);
return true;
}
i searched on internet but can't find any suitable answer.

Uri.fromFile returning null?

For some reason outputFileUri returns null in my onActivityResult:
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
I don't understand why. Please take a look at my code and see where I go wrong. I let the user take 4 images by choosing from gallery or using the camera. The ones that the user takes with the camera won't show presumably because their uri is null. outputFileUri is a class variable.
takePictureIntent():
private void dispatchTakePictureIntent() {
for(int i = 0; i < 4; i++) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
outputFileUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Log.w("error","IOException");
}catch (NullPointerException nullEx) {
Log.w("error","NullPointerException");
}
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
if(id.equals(HAPPY_ID))
startActivityForResult(chooserIntent, REQUEST_HAPPY_PHOTO);
if(id.equals(SURPRISED_ID))
startActivityForResult(chooserIntent, REQUEST_SURPRISED_PHOTO);
if(id.equals(AFRAID_ID))
startActivityForResult(chooserIntent, REQUEST_AFRAID_PHOTO);
if(id.equals(UPSET_ID))
startActivityForResult(chooserIntent, REQUEST_UPSET_PHOTO);
if(id.equals(SAD_ID))
startActivityForResult(chooserIntent, REQUEST_SAD_PHOTO);
}
}
}
onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_HAPPY_PHOTO || requestCode == REQUEST_SURPRISED_PHOTO || requestCode == REQUEST_AFRAID_PHOTO ||
requestCode == REQUEST_UPSET_PHOTO || requestCode == REQUEST_SAD_PHOTO) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
//Log.d("doing ids", "right before id");
//Log.d("doing ids", "id is " + id);
if(requestCode == REQUEST_HAPPY_PHOTO) {
//Log.d("doing ids", "in happy");
happyList.add(selectedImageUri);
}
if(requestCode == REQUEST_SURPRISED_PHOTO) {
//Log.d("doing ids", "in surprised");
surprisedList.add(selectedImageUri);
}
if(requestCode == REQUEST_AFRAID_PHOTO) {
//Log.d("doing ids", "in surprised");
afraidList.add(selectedImageUri);
}
if(requestCode == REQUEST_UPSET_PHOTO) {
//Log.d("doing ids", "in surprised");
upsetList.add(selectedImageUri);
}
if(requestCode == REQUEST_SAD_PHOTO) {
//Log.d("doing ids", "in surprised");
sadList.add(selectedImageUri);
}
}
}
}
My createImageFile():
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 = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
I had a similar problem, I solved it by holding a reference to the URI that I pass to the Intent. This allowed me to not rely on the Intent to return the URI.
Here's the code:
private Uri startCameraFileUri;
private void startCameraIntent() {
final Intent intentCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
startCameraFileUri = Uri.fromFile(Utils.getNewFile());
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, startCameraFileUri);
intentCamera.putExtra("return-data", true);
startActivityForResult(intentCamera, IConstants.REQUEST_TAKE_PICTURE);
} catch (Exception e) {
e.printStackTrace();
}
}
public void openGalleryIntent() {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
final Intent openGalleryIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
openGalleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
openGalleryIntent.setType("image/*");
openGalleryIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(
Intent.createChooser(openGalleryIntent, getString(R.string.PROFILE_PIC_LIBRARY)),
IConstants.REQUEST_GALLERY);
} else {
final Intent openGalleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
openGalleryIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(openGalleryIntent, getString(R.string.PROFILE_PIC_LIBRARY)), IConstants.REQUEST_GALLERY);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
final Uri uri;
if(data != null) {
uri = data.getData();
}
else{
uri = startCameraFileUri;
}
switch (requestCode) {
case IConstants.REQUEST_GALLERY:
case IConstants.REQUEST_TAKE_PICTURE:
try {
if (!uri.toString().isEmpty()) {
loadUserPhoto(uri.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}

Categories

Resources