I am experiencing odd behaviors. I am trying to bring up the gallery using an Intent. And then onActivityResult() I want to take the Uri and convert it to a Bitmap. The issue I am facing is that selecting an image first causes my phone to freeze for several seconds. And then by the time it returns to onActivityResult() the resultCode value is -1, even though I selected an image. Am I missing something in my steps?
Launch Gallery Intent
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_REQUEST_CODE);
My onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE) {
Uri selectedImageUri = data.getData();
if (selectedImageUri != null) {
try {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(
selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap mBitmap = BitmapFactory.decodeFile(filePath);
LogUtil.e(TAG, "mBitmap: " + mBitmap);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
Intent intent = new Intent(CameraActivity.this,
SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("image", bs.toByteArray());
startActivity(intent);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
return;
}
}
Update:
I have permission in manifest. I am receiving the correct Uri too. But after selecting an image I am always receiving resultCode = -1. It seems that I am receiving a failed binder transaction.
Am I missing any permissions maybe? Thank you in advance!
to make this code work you need to have, write permission check if you have this in your manifest.
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Related
I recently fixed a known bug in my app that occurs on some devices; when the user takes a photo from an intent launched from my app, in the onActivityResult Uri uri = intent.getData(); returns null. I managed to fix that in the suggested manner. However I get the exact same issue when the user needs to Select a picture from his phone's photo gallery. The same intent.getData() == null.
Starting the intent:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
R.id.SELECT_IMAGE_ACTIVITY_REQUEST_CODE);
onActivityResult:
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 filePath = cursor.getString(columnIndex);
cursor.close();
dataHasChanged(ACTION_PICTURE, filePath);
PS: Strangely enough if I start the intent like shown below I can get the intent.getData() but only if I use the "Gallery" app on my samsung s4 and not the GooglePhotos app.
Intent pickImageIntent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (pickImageIntent.resolveActivity(getPackageManager()) != null)
startActivityForResult(pickImageIntent, R.id.SELECT_IMAGE_ACTIVITY_REQUEST_CODE);
I am unsure on how to proceed. I find the entire Android intents affair very confusing sometimes.
I'm giving you code for your reference:
Use following code after clicking pic from your app:
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,"Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
Below code will be in your onActivityResult():
if (requestCode == PICK_FROM_GALLERY) {
if (resultCode != RESULT_CANCELED) {
Bundle extras2 = data.getExtras();
if (extras2 != null) {
photo = extras2.getParcelable("data");
bitmap = photo;
profile_imageView.setImageBitmap(photo);
new ImageUploadTask().execute();
}
}
}
Hope this will solve your problem.
static final int REQUEST_GALLERY_IMAGE = 14;
----------
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_GALLERY_IMAGE );
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY_IMAGE && resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imagePreview.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I'm looking for a way to open the Android gallery application from an intent.
I do not want to return a picture, but rather just open the gallery to allow the user to use it as if they selected it from the launcher (View pictures/folders).
I have tried to do the following:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
However this is causing the application to close once I select a picture (I know this is because of the ACTION_GET_CONTENT), but I need to just open the gallery.
Any help would be great.
Thanks
This is what you need:
ACTION_VIEW
Change your code to:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I hope this will help you. This code works for me.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
ResultCode is used for updating the selected image to Gallery View
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);
if (cursor == null || cursor.getCount() < 1) {
return; // no cursor or no record. DO YOUR ERROR HANDLING
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if(columnIndex < 0) // no column index
return; // DO YOUR ERROR HANDLING
String picturePath = cursor.getString(columnIndex);
cursor.close(); // close cursor
photo = decodeFilePath(picturePath.toString());
List<Bitmap> bitmap = new ArrayList<Bitmap>();
bitmap.add(photo);
ImageAdapter imageAdapter = new ImageAdapter(
AddIncidentScreen.this, bitmap);
imageAdapter.notifyDataSetChanged();
newTagImage.setAdapter(imageAdapter);
}
You can open gallery using following intent:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
If you want to get result URI or do anything else use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
Tested on Android 4.0+
Following can be used in Activity or Fragment.
private File mCurrentPhoto;
Add permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
Add Intents to open "image-selector" and "photo-capture"
//A system-based view to select photos.
private void dispatchPhotoSelectionIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
this.startActivityForResult(galleryIntent, REQUEST_IMAGE_SELECTOR);
}
//Open system camera application to capture a photo.
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(App.Instance.getPackageManager()) != null) {
try {
createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (mCurrentPhoto != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhoto));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Add handling when getting photo.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_IMAGE_SELECTOR:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = App.Instance.getContentResolver().query(data.getData(), filePathColumn, null, null, null);
if (cursor == null || cursor.getCount() < 1) {
mCurrentPhoto = null;
break;
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if(columnIndex < 0) { // no column index
mCurrentPhoto = null;
break;
}
mCurrentPhoto = new File(cursor.getString(columnIndex));
cursor.close();
} else {
mCurrentPhoto = null;
}
break;
case REQUEST_IMAGE_CAPTURE:
if (resultCode != Activity.RESULT_OK) {
mCurrentPhoto = null;
}
break;
}
if (mCurrentPhoto != null) {
ImageView imageView = (ImageView) [parent].findViewById(R.id.loaded_iv);
Picasso.with(App.Instance).load(mCurrentPhoto).into(imageView);
}
super.onActivityResult(requestCode, resultCode, data);
}
As you don't want a result to return, try following simple code.
Intent i=new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivity(i);
if somebody still getting the error, even after adding the following code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
then you might be opening the intent in another class (by calling) due to this the app will crash when you click the button.
SOLUTION FOR THE PROBLEM
Put intent in the class file which is connected to the button's layout file.
for example- activity_main.xml contains the button and it is connected to MainActivity.java file. but due to fragmentation, you are defining the intent in some other class(lets says Activity.java) then your app will crash unless you place the intent in MainActivity.java file. I was getting this error and it is resolved by this.
I used startActivityForResult to pick a picture from gallery and then used onActivityResult for bring the result.
when i use getPath() for the intent result to send the path to another activity to set the source of that picture , the path is incorrect and is another way that the picture is not located there .
the picture is located in sdcard and located at : "mnt/sdcard/pictures/lambo"---- but getpath() his returns : "external/images/media/17
photopicker :
private void photopicker() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PHOTO);
}
onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String add;
add = selectedImage.getPath(); // don't work
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
selectedPhoto = BitmapFactory.decodeStream(imageStream);
// add = selectedImage.getPath(); // don't work
Intent intent = new Intent(MainActivity.this, PicViewer.class);
intent.putExtra("add", add);
startActivity(intent);
}
}
}
You can try this:
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I am starting a request for an image pick:
Intent intent = new Intent();
intent.setType( "image/*" );
intent.setAction( Intent.ACTION_GET_CONTENT );
startActivityForResult( Intent.createChooser( intent, "Choose"), PHOTO_GALLERY );
And getting the data back out in onActivityResult:
if( resultCode == Activity.RESULT_OK && requestCode == PHOTO_GALLERY )
{
U.log( data.getData() );
Bitmap bm = ... // built from the getData() Uri
this.postImagePreview.setImageBitmap( bm );
}
When I launch the Intent, I see some folders, such as sdcard, Drop Box, MyCameraApp, and so on.
If I chose a picture from sdcard, when I load the preview, it is the completely wrong image. The other folders don't seem to be giving me this problem.
Does anyone know why it'd let me pick one image, then give me the Uri for another?
EDIT: Here are some exampled logged getData()s:
Good:
content://com.google.android.gallery3d.provider/picasa/item/5668377679792530210
Bad:
content://media/external/images/media/28
EDIT: I'm still having issues, when picking from the sdcard folder of gallery.
Here is a bit more expansion of what I'm doing in onActivityResult:
// cursor
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = mContext.getContentResolver().query( selectedImage, filePathColumn, null, null, null );
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex( filePathColumn[0] );
String filePath = cursor.getString( columnIndex );
cursor.close();
// Cursor: /mnt/sdcard/Pic.jpg : /mnt/sdcard/Pic.jpg
U.log( "Cursor: " + filePath + " : " + Uri.parse( filePath ) );
// "regular"
// Regular: content://media/external/images/media/28 : content://media/external/images/media/28
U.log( "Regular: " + data.getDataString() + " : " + Uri.parse( data.getDataString() ) );
// Regular 2: content://media/external/images/media/28 : content://media/external/images/media/28
U.log( "Regular 2: " + data.getData() + " : " + data.getData() );
mPostImagePreview.setImageBitmap( BitmapFactory.decodeFile( filePath ) );
mPostImagePreview.setVisibility( View.VISIBLE );
They still set the wrong image. If I go into the Gallery, long press the image, and view its details I get:
TItle: Pic
Time: May 2, 2012
Width: 720
Height: 1280
Orientation: 0
File size: 757KB
Maker: Abso Camera
Model: Inspire 4G
Path: /mnt/sdcard/Pic.jpg
So, the Gallery is telling me the path is the same as the pick action, and the Gallery is rendering it correctly. So why on earth is it not rendering if I set it from onActivityResult?
Also, this is the code I'm using to fire the Intent now:
private void selectPhoto()
{
Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
intent.setType( "image/*" );
( ( Activity )mContext ).startActivityForResult( Intent.createChooser( intent, "Select Picture" ), PHOTO_GALLERY );
}
Sometimes the thumbnails in the gallery app can be outdated and show thumbnails for a different image. This can happen when the image ids are reused, for example when an image gets deleted and a new one is added using the same id.
Manage Apps > Gallery > Clear Data can fix this problem then.
This is the code to open gallery. However this the same what you have done. Also see the onActivityResult code which I used to retrive the selected image.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PHOTO_GALLERY);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PHOTO_GALLERY:
if (resultCode == RESULT_OK) {
Uri selectedImageUri = Uri.parse(data.getDataString());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(
getApplicationContext().getContentResolver(),
selectedImageUri);
this.postImagePreview.setImageBitmap( bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
private static int RESULT_LOAD_IMAGE = 1;
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
OnActivity Result
#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();
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();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
try this one
//Put this code on some event
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE);
// When above event fire then its comes to this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK && requestCode==1){
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]);
filePath = cursor.getString(columnIndex);
cursor.close();
// Use it as per recruitment
actualBitmap =BitmapFactory.decodeFile(filePath);
}
}
Try this,
public class SelectPhotoActivity extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, SELECT_PICTURE);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
// here you can set the image
}
}
}
}
In Application i open gallery and select image i have to show that image in dialog box..
bu sometimes it returen bitmap value =null.. and somtimes it has bitmap value does not show dialog box.. it throughs exceptioni.e
java.lang.NullPointerException
04-16 10:11:52.310: WARN/System.err(1395): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:432)
04-16 10:11:52.310: WARN/System.err(1395): at myclassname.onActivityResult
for iopen gallery i used below code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) context).startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_FROM_FILE);
Foe getting data from gallery i used this code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK)
{
Uri selectedImage = data.getData();
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Plz help ..
In you onActivityResult change the code to receive the image to this code,
if (resultCode == RESULT_OK && requestCode == PICK_FROM_FILE) {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String tmppath = cursor.getString(column_index); // get path of image
Bitmap mBitmap = BitmapFactory.decodeFile(tmppath); // decode path into bitmap
iv.setImageBitmap(mBitmap); // set image to imageview
}