Pick photo from gallery in android 5.0 - android

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

Related

How to change the shape of an uploaded image (Image from photo gallery) into circular form

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

Getting Image from gallery in android

I've been trying to get an image from gallery in this app and then on a button click I want to upload to my PHP server.
The "selectedImagePath" comes as null why?
If anyone has a solutions please help me! Thanks in advance.
onCreate()
img = (ImageView) findViewById(R.id.ImageView01);
Button browse = (Button) findViewById(R.id.Button01);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
});
onActivityResult()
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
System.out.println(selectedImageUri);
selectedImagePath = getPath(selectedImageUri);//returns as null
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
getPath()
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);
}
try this
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == Activity.RESULT_OK && data != null){
String realPath;
// SDK < API11
if (Build.VERSION.SDK_INT < 11) {
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
}
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19) {
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
}
// SDK > 19 (Android 4.4)
else {
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
}
System.out.println("Image Path : " + realPath);
}
}
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.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;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
the code for getRealPath class is not mine, I din't write down the website.
When you get the data, create file from that path first and then get that file's path as "selectedImagePath". Then you will get actual path of image on external storage: Try below code:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
File myFile = new File(selectedImageUri);
System.out.println(selectedImageUri);
selectedImagePath = myFile.getPath();
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
try this code,
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
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);
}
Try below code
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri uri = data.getData();
String[] filepath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, filepath, null,
null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filepath[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
System.out.println("Image Path : " + filePath);
}
I've spent some time on this problem and eventually I found the fully working solution().
A.
It's taken from cordova-plugin-camera which can be found here:
public static String getRealPath(final Uri uri, final Context context) {
String realPath = null;
if (Build.VERSION.SDK_INT < 11) {
realPath = FileHelper.getRealPathFromURI_BelowAPI11(context, uri);
// SDK >= 11
} else {
realPath = FileHelper.getRealPathFromURI_API11_And_Above(context, uri);
}
return realPath;
}
both methods are provided in [FileHelper.class]:
https://github.com/apache/cordova-plugin-camera/blob/06d609cfa4871b4a2811f5a8f7f0a822733209b9/src/android/FileHelper.java
I don't want to duplicate the code, links are provided instead because solutions are quite complex. /I consider the fact that they could expire but hoping they won't/
B.
Here is a link to the source code of a sample project [RealPathUtil.java]: https://github.com/hmkcode/Android/blob/master/android-show-image-and-path/src/com/hmkcode/android/image/RealPathUtil.java
C.
Another question in here that didn't find much attention. [Stack Overflow Post]: https://stackoverflow.com/a/36714242

How to get image path from camera intent?

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

Getting Uri Null in capture photo from camera intent in samsung mobile

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

Not able to select few photos from Gallery in Android

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.

Categories

Resources