In my application I am giving the user an option to choose a picture from gallery or click it from a camera, using the inbuilt camera and gallery features and setting intents for the same. Somehow on Orientation change I lose the data passed from these intents. After looking up I came to know that orientation change causes activity to redraw and re-initialize. Now I want to use Bundle and OnConfigurationChange and save my extras. I am clueless about how to achieve it, a detailed answer could be helpful. Below is my code:
if(i==0){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == 1337 && resultCode== Activity.RESULT_OK) {
Bundle extras = data.getExtras();
if (extras != null){
TitmapFactory.Options options = new TitmapFactory.Options();
options.inSampleSize = 1;
options.inPurgeable = true;
options.inInputShareable = true;
thumbnail = (Titmap) data.getExtras().get("data");
// imgview.setImageTitmap(thumbnail);
image(thumbnail);
} else {
Toast.makeText(CreateProfile.this, "Picture NOt taken", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
thumbnail = (BitmapFactory.decodeFile(picturePath));
image(thumbnail);
}
Related
I am asking the user for the access to the gallery through the code as a listener here:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
However, I am confused as to how I would set a variable to the photo selected.
Where would I put the code to set a variable as the photo selected?
Thanks :)
First you have to override onActivityResult to get the uri of the file selected image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == SELECT_PHOTO) {
if (resultCode == RESULT_OK) {
if (intent != null) {
// Get the URI of the selected file
final Uri uri = intent.getData();
useImage(uri);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
Then define useImage(Uri) to use the image
void useImage(Uri uri)
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
//use the bitmap as you like
imageView.setImageBitmap(bitmap);
}
You can do it like this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
Alternative for Akash Kurian Jose answer
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
I always use
fun getBitmap(file: Uri, cr: ContentResolver): Bitmap?{
var bitmap: Bitmap ?= null
try {
val inputStream = cr.openInputStream(file)
bitmap = BitmapFactory.decodeStream(inputStream)
// close stream
try {
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}catch (e: FileNotFoundException){}
return bitmap
}
It works both for photos from gallery and photos from camera.
Larger issue about it: Picasso unable to display image from Gallery
Open Gallery using this method:
private void openGallery(){
if (Build.VERSION.SDK_INT <19){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_picture)),GALLERY_INTENT_CALLED);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
}
}
Then you are able to read convert Uri to Bitmap using afromentioned ContentResolver.openInputStream or set image ImageView.setImageUri(Uri)
If you want to display the selected image to any particular ImageView.
Suppose we have RC_PHOTO_PICKER = 1 then these lines of code should do the magic
private void openPhotoPicker() {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, false);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Complete Action Using"), RC_PHOTO_PICKER);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK && data != null) {
Uri pickedImage = data.getData();
//set the selected image to ImageView
mImageView.setImageURI(pickedImage);
}
}
And simply call the openPhotoPicker() method afterwards
I am trying to give the user the option to either choose an image from the phone's storage or take one with the phone's camera app and then display that image in an imageView. With the help of this and this question I am able to display the image when it is choosen from the storage. However if I choose to take a picture with camera although I don't get an error the image is not shown in the imageView.
The function for choosing the picture looks like:
public void choosePic(View view) {
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
Intent.EXTRA_INITIAL_INTENTS,
new Intent[] { takePhotoIntent }
);
startActivityForResult(chooserIntent, SELECT_PICTURE);
}
After that it is handled by
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
//User had pick an image.
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
image = (ImageView) findViewById(R.id.imageView);
image.setImageURI(_uri);
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
}
EDIT
With #Murtaza Hussain's helps I was able to find a working solution:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("requestCode",""+requestCode);
if(requestCode == PICK_IMAGE && resultCode==RESULT_OK && data != null && data.getData() != null) {
Uri _uri = data.getData();
//User had pick an image.
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
image = (ImageView) findViewById(R.id.imageView);
image.setImageURI(_uri);
cursor.close();
}
else if(requestCode== PICK_IMAGE && resultCode==RESULT_OK && data.getData() == null){
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
image =(ImageView) findViewById(R.id.imageView);
image.setImageBitmap(thePic);
}
super.onActivityResult(requestCode, resultCode, data);
}
You need to add code for it in onActivityResult()
if(requestCode==0 && resultCode==RESULT_OK ){
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
image =(ImageView) findViewById(R.id.imageView);
image.setImageBitmap(thePic);
}
In your activity when to capture image from camera. write the below code.
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"/imageLarge"+System.currentTimeMillis()+".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, 111);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
In onActivityResult() write the below code..
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 111:
if(resultCode == RESULT_OK)
{
Log.v("","After camera capture path is --> "+mImageCaptureUri.toString().substring(8));
Bitmap bitmap=BitmapFactory.decodeFile(mImageCaptureUri.toString().substring(8));
image.setImageBitmap(bitmap);
}
else
{
}
}
}
Do not forget to add one permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In case of any query, Please let me know. Thanks.
I am little stuck on a query. searched a lot but didn't get desired result..So please help me to Solve this problem..
I want to Select Image from Gallery and I got success in it.. but now I want to get thumbnail path too..
I know I can Create Thumbnail From Image path...but i want string path of thumbnail so i can use it in array....
So When I select any image from gallery I want these two paths..
Image Path
Thumbnail Path or ID of Selected Image
My Code..
to Open Gallery..
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMAGE);
OnActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
path = null;
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
path = cursor.getString(columnIndex);
long imageId = cursor.getLong(columnIndex); //getting 0 here... i thought it could give me image id.. :p
Log.v("AddEventDataActivity", "Selected Image Path : " + path); // getting image path successfully...
Log.v("AddEventDataActivity", "Selected Image ID : " + imageId); // ???
cursor.close();
// tried this but not succeed.. :(
Cursor thumbcursor = MediaStore.Images.Thumbnails
.queryMiniThumbnail(getContentResolver(), imageId,
MediaStore.Images.Thumbnails.MINI_KIND, null);
if (thumbcursor != null && thumbcursor.getCount() > 0) {
thumbcursor.moveToFirst();// **EDIT**
thumbpath = thumbcursor.getString(thumbcursor
.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
}
thumbcursor.close();
Log.v("THUMB", "THUMBNAIL PATH : " + thumbpath); // no value to thumbpath...
}
}
I could not find how to solve that...
Any help would be helpful...
for getting Thumbnail
Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
getContentResolver(), selectedImageUri,
MediaStore.Images.Thumbnails.MINI_KIND,
(BitmapFactory.Options) null );
where selectedImageUri = data.getData();
I know this is old, but this worked for me:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
try {
Long thumbId = Long.parseLong(selectedImage.getLastPathSegment());
Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
getContentResolver(),
thumbId,
MediaStore.Images.Thumbnails.MINI_KIND,
null
);
} catch (NumberFormatException e) {
//Handle exception
}
}
}
I am a new to Android Development. I wish to select an image or a video from the Gallery of an Android Device. Store it in a variable of typeFile. I am doing this, since I need to upload the image/video on dropbox using the Android API from my application. The constructor takes in the fourth parameter of the type File. I am not sure, what to pass as a file since all the examples I searched display the image chosen in an ImageView by using the url and making a bitmap.
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Here is the code, I have.
final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
//to get image and videos, I used a */"
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, 1);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
yourSelectedImage = BitmapFactory.decodeFile(filePath);
return cursor.getString(column_index);
}
All you need to do is just create a File variable with the path of image which you've selected from gallery. Change your OnActivityResult as :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
File imageFile = new File(imagepath);
}
}
this works for image selection. also tested in API 29,30. if anyone needs it.
private static final int PICK_IMAGE = 5;
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "select image"),
PICK_IMAGE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURIForGallery(selectedImageUri);
File imageFile = new File(selectedImagePath);
}
}
public String getRealPathFromURIForGallery(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(uri, projection, null,
null, null);
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
assert false;
cursor.close();
return uri.getPath();
}
Try this
You can try this also
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK && data != null)
{
File destination = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
//You will get file path of captured camera image
Bitmap photo = (Bitmap) data.getExtras().get("data");
iv_profile.setImageBitmap(photo);
}
}
I'm using an intent like this:
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
And in onActivityResult() I have this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return; // user cancelled
}
Uri imageUri = data.getData();
if (imageUri == null) {
// (code to show error message goes here)
return;
}
// Get image path from media store
String[] filePathColumn = { android.provider.MediaStore.MediaColumns.DATA };
Cursor cursor = this.getContentResolver().query(imageUri, filePathColumn,
null, null, null);
if (cursor == null || !cursor.moveToFirst()) {
// (code to show error message goes here)
return;
}
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
cursor.close();
if (imagePath == null) {
// error happens here
}
}
When I select images from particular albums like "Posts", "Profile Photos" (see screenshot) I'm unable to get the image path in onActivityResult(). Images from other albums can be selected with no problems.
I've tried adding intent.putExtra("return-data", true) but data.getExtras() returns null in onActivityResult().
There is similar question here, but no one answered it.
Please help!
hops this will helps you ....
ACTIVITYRESULT_CHOOSEPICTURE is the int you use when calling startActivity(intent, requestCode);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == ACTIVITYRESULT_CHOOSEPICTURE) {
BitmapFactory.Options options = new BitmapFactory.Options();
final InputStream ist = ontext.getContentResolver().openInputStream(intent.getData());
final Bitmap bitmap = BitmapFactory.decodeStream(ist, null, options);
ist.close();
}
}
if above code doesn't work than just refer this link... it will surly shows the way
http://dimitar.me/how-to-get-picasa-images-using-the-image-picker-on-android-devices-running-any-os-version/
try this:
String selectedImagePath = imageUri.getEncodedPath();
it works for me using gallery image picker
maybe this:
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());