How to resolve orphan case? - java

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

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

Why is the image chosen from gallery with bigger size not showing?

if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
imageuri = data.data
bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageuri)
try {
if(bitmap != null){
Toast.makeText(applicationContext, "Not empty",Toast.LENGTH_SHORT).show()
imageView?.setImageURI(imageuri)
}else{
Toast.makeText(applicationContext, "It is empty", Toast.LENGTH_SHORT).show()
}
} catch (e: IOException) {
e.printStackTrace()
displayExceptionMessage(e.message)
}
}
Other images with a size of 2MB and below are loading but when it is higher than 2MB it is not displaying. Can someone tell the mistake? Thanks
It is because you are trying to read with bitmap.
You can do like this :
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
{
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
imageuri = data.data
try {
imageView!!.setImageUri(imageuri)
} catch (e: IOException) {
e.printStackTrace()
}
This solved my problem:
imageView?.let {
Glide.with(this)
.load(imageuri)
.into(it)}

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

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!

i want to crop an image to set profile

I am new here and learning about android development. I want to crop image to set profile pic. when i used below codes its not done its jump to catch(something went wrong). kindly please help me solve this problem. used Image view on xml and got permission read and write on mainfest. And used ArthurHub/Android-Image-Cropper for cropping function
enter code here select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
premission();
if (pre == 2) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
Log.d("pp", "pp");
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{ super.onActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && null != data)
{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
Uri selectedImage = data.getData();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
Uri selectedImage = result.getUri();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
profileimage.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
Drawable myDrawable = profileimage.getDrawable();
profileimage.buildDrawingCache();
Bitmap bmap = profileimage.getDrawingCache();
BitmapDrawable bitmapDrawable = ((BitmapDrawable) myDrawable);
Bitmap bitmap1 = bitmapDrawable.getBitmap();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, stream);
imageInByte = stream.toByteArray();
encoded = Base64.encodeToString(imageInByte, Base64.DEFAULT);
} else
{
Toast.makeText(this, "You have not picked Image",
Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e)
{
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}

Problem retrieving picture from Camera intent in other than myself device (Oreo)

I am trying to get image from camera intent. Its working nice but only in my device (oreo / 8.1.0). I generate unsigned apk and tried to run in other device (pie and lolipop)but its not working.
I search stackoverflow and other sites, but people asked question about "camera intent problem in lolipop". My question is something different (I think).
I tried to check sdk version and apply different code. I.e. as per one answer from stackoverflow I used this code Picasso.get().load(file).into(imageView); instead of Picasso.get().load(photoURI).into(imageView); in LOLIPOP but its not working.
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null; // Create the File where the photo should go
try {
photoFile = createImageFile();
tempPhoto = photoFile;
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.package.appname.fileprovider",
photoFile);
tempPhoto = photoFile;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
Code for createImageFile function:
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 = image.getAbsolutePath();
return image;
}
Receiving result here
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
File file = new File(mCurrentPhotoPath);
Picasso.get().load(file).into(imageView);
// Bitmap bitmap = MediaStore.Images.Media
// .getBitmap(this.getContentResolver(), Uri.fromFile(file));
// if (bitmap != null) {
// imageView.setImageBitmap(bitmap);
// }
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
File file = new File(mCurrentPhotoPath);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.fromFile(file));
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
} catch (Exception error) {
error.printStackTrace();
}
}
Can anyone help me to give accurate result in all sdk versions? Please help me. Thanks in advance.
Try this:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri uri = intent.getData(); // you need take uri of image
imageView.setImageURI(uri); // you don't need of picasso to load local images
// Picasso.get().load(file).into(imageView);
// Bitmap bitmap = MediaStore.Images.Media
// .getBitmap(this.getContentResolver(), Uri.fromFile(file));
// if (bitmap != null) {
// imageView.setImageBitmap(bitmap);
// }
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
File file = new File(mCurrentPhotoPath);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.fromFile(file));
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
} catch (Exception error) {
error.printStackTrace();
}
}

Categories

Resources