I'am invoking default gallery app from my app to select any photo. Below is my code to get the selected image path from gallery. It's working fine for all the photos except few. When i select any of PICASA uploaded photos from Gallery, app is force closing. Please help me.
Inside 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 selectedPhotoPath = cursor.getString(columnIndex).trim(); <<--- NullPointerException here
cursor.close();
bitmap = BitmapFactory.decodeFile(selectedPhotoPath);
......
Sometimes data.getData(); returns null depending on the app you use to get the picture. A workaround for this is to use the above code in onActivityResult:
/**
*Retrieves the path of the image that was chosen from the intent of getting photos from the galery
*/
Uri selectedImageUri = data.getData();
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String filename = getImagePath(selectedImageUri);
String chosenPath;
if (filename != null) {
chosenPath = filename;
} else {
chosenPath = filemanagerstring;
}
The variable chosenPath will have the correct path of the chosen image. The method getImagePath() is this:
public String getImagePath(Uri uri) {
String selectedImagePath;
// 1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
} else {
selectedImagePath = null;
}
if (selectedImagePath == null) {
// 2:OI FILE Manager --- call method: uri.getPath()
selectedImagePath = uri.getPath();
}
return selectedImagePath;
}
Please try below code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
....
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OR
Please check below link
OR
How to pick an image from gallery (SD Card) for my app?
String ImagePath = "";
private void setImageFromGallery(Intent data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Log.i("choosepath", "image" + picturePath);
ImagePath = picturePath;
} else {
ImagePath = selectedImage.getPath(); // Add this line
}
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
Bitmap bitmap = Utilities.rotateImage(pictureImagePath);
}
Current Android system (first version -> 2.3.3 -> even 4.4.2) looks like not able to selected multiple files, so you need custom gallery to do that.
Afer researched so many times, I found Custom Camera Gallery library can help you do that thing already.
Related
In my android application I select photo from phone's gallery or phone's storage file memory and view it on Image-view. Moreover, I also want the selected photo's Timestamp.
I got succeed to fetch photo from gallery and show it on to image-view. However, I didn't get the selected photo's Timestamp.
Any suggestion, how to get selected photo's timestamp?
Try this :
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String picturePath = getPath(getActivity().getApplicationContext(), selectedImageUri );
File file = new File(picturePath);
Date fileDate = new Date(file.lastModifiedDate());
int timestamp = Math.round(fileDate.getTime()/1000);
}
}
public static String getPath(Context context, Uri uri) {
String result = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if(cursor != null){
if ( cursor.moveToFirst() ) {
int column_index = cursor.getColumnIndexOrThrow( proj[0] );
result = cursor.getString( column_index );
}
cursor.close( );
}
if(result == null) {
result = "Not found";
}
return result;
}
How to change the shape of an uploaded image (Image from photo gallery) into circular form in android eclipse.
This is how you use it :
//this the button which allows you to access the gallery
pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gallery();
}
});
//this allows you select one image from gallery
public void gallery() {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
//when you start activity for result and choose an image, the code will automatically continue here
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Uri current_ImageURI = data.getData();
selectedImagePath = getPath(current_ImageURI);
image.setImageDrawable(RoundedBitmapDrawableFactory.create(getResources(),selectedImagePath));
}
}
}
public String getPath(Uri contentUri) {
// we have to check for sdk version because from lollipop the retrieval of path is different
if (Build.VERSION.SDK_INT < 21) {
// can post image
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else {
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
}
Now the two functions below :
decode the sample size of the bitmap (to do correct scaling) and the other extracts the bitmap from the path are also no longer to be used
The Circular Bitmap class is no longer to be used
For better understanding please use this link fr reference : http://developer.android.com/reference/android/support/v4/graphics/drawable/RoundedBitmapDrawableFactory.html
I encounter a problem by picking images from gallery with android 5.0. My code for starting intent is:
private void takePictureFromGallery()
{
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_FROM_FILE);
}
and here is function called in onActivityResult() method for request code PICK_FROM_FILE
private void handleGalleryResult(Intent 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]);
// field declaration private String mTmpGalleryPicturePath;
mTmpGalleryPicturePath = cursor.getString(columnIndex);
cursor.close();
// at this point mTmpGalleryPicturePath is null
...
}
For previous versions than 5.0 this code always work, using com.android.gallery application. Google Photos is default gallery application on Android 5.0.
Could be this problem depends by application or is an issue of new android OS distribution?
EDIT
I understand the problem: Google Photos automatically browse content of its backupped images on cloud server. In fact trying pratice suggest by #maveň if i turn off each internet connections and after choose an image, it doesn't get result by decoding Bitmap from InputStream.
So at this point question become: is there a way in android 5.0 to handle the Intent.ACTION_PICK action so that system browse choose in local device image gallery?
I found solution to this problem combining following methods.
Here to start activity for pick an image from gallery of device:
private void takePictureFromGallery()
{
startActivityForResult(
Intent.createChooser(
new Intent(Intent.ACTION_GET_CONTENT)
.setType("image/*"), "Choose an image"),
PICK_FROM_FILE);
}
Here to handle result of intent, as described in this post, note that getPath() function works differently since android build version:
private void handleGalleryResult(Intent data)
{
Uri selectedImage = data.getData();
mTmpGalleryPicturePath = getPath(selectedImage);
if(mTmpGalleryPicturePath!=null)
ImageUtils.setPictureOnScreen(mTmpGalleryPicturePath, mImageView);
else
{
try {
InputStream is = getContentResolver().openInputStream(selectedImage);
mImageView.setImageBitmap(BitmapFactory.decodeStream(is));
mTmpGalleryPicturePath = selectedImage.getPath();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#SuppressLint("NewApi")
private String getPath(Uri uri) {
if( uri == null ) {
return null;
}
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor;
if(Build.VERSION.SDK_INT >19)
{
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
}
else
{
cursor = getContentResolver().query(uri, projection, null, null, null);
}
String path = null;
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
return path;
}
takePictureFromGallery() is invoked from onActivityResult
Thats all!!
Try this:
//5.0
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, CHOOSE_IMAGE_REQUEST);
Use the following in the onActivityResult:
Uri selectedImageURI = data.getData();
input = c.getContentResolver().openInputStream(selectedImageURI);
BitmapFactory.decodeStream(input , null, opts);
Update
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri);
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
if( uri == null ) {
return null;
}
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = 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);
}
return uri.getPath();
}
} }
tempPath will store the path of the ImageSelected
Check this for more detail
i work with android 2.1 , and i want to get real path from Camera intent result. I read Get Path of image from ACTION_IMAGE_CAPTURE Intent but it is for android 2.2.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_RESULT)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imv.setImageBitmap(thumbnail);
Uri selectedImageUri = data.getData();
String path = getRealPathFromURI(selectedImageUri);
}
}
private String getRealPathFromURI(Uri contentUri)
{
try
{
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);
}
catch (Exception e)
{
return contentUri.getPath();
}
}
Its above code works in some mobile but does not work in samsung mobile in my case so I implemented the common logic for all devices.
When I capture the photo from camera so I implement a logic using Cursor and iterate the cursor and get the last photo path which is capture from camera.
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
}
The answer given by #TGMCians works but i was able to improvise it further as below
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToLast()){
Uri fileURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
String fileSrc = fileURI.toString();
cursor.close();
}
I am getting null in contenturi in samsung phones while capturing photo from camera but rest of others phones its working fine.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
Uri contentUri = data.getData();
if(contentUri!=null)
{
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();
imageUri = Uri.parse(cursor.getString(column_index));
}
tempBitmap = (Bitmap) data.getExtras().get("data");
mainImageView.setImageBitmap(tempBitmap);
isCaptureFromCamera = true;
}
}
This above code works in some mobile but does not work in samsung mobile in my case, so I implemented the common logic for all devices.
After capturing the photo from camera, I implement a logic using Cursor and iterate the cursor to get the path of last captured photo from camera.The below code works fine on any device.
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
}
Hi i am also facing this issue to like I am checking app on MOTO G its not working but on Samsung devices its working So i do Below coding please check:-
Uri selectedImageUri = data.getData();
try {
selectedImagePath = getPathBelowOs(selectedImageUri);
} catch (Exception e) {
e.printStackTrace();
}
if (selectedImagePath == null) {
try {
selectedImagePath = getPathUpperOs(selectedImageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPathBelowOs(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);
}
/**
* Getting image from Uri
*
* #param contentUri
* #return
*/
public String getPathUpperOs(Uri contentUri) {// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
new String[] { id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}