Selecting a Photo from the Gallery and getting its TimeStamp - android

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

Related

Image path null in Android

I have code like this, the problem is when i want to save it to sqlite, the error message shown that i got null in image path.
Here is the main activity
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
System.out.println("Data Image : "+selectedImageUri);
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
image1.setVisibility(View.VISIBLE);
image1.setImageURI(selectedImageUri);
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
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);
}
I use this method to take photos from camera.
private void capturePhoto() {
// save this Uri in a field variable.
uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, CAMERA_REQUEST);
}
then onActivityResult will look like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
// use the field Uri, it now points to the path to the image taken from the camera.
}
}
In manifest file set permission
Check permission granted in onActivityResult method and after its granted READ_EXTERNAL_STORAGE
If it has Permission then call doCreatePath() and set the same in onRequestPermissionsResult on permission granted.
void doCreatePath()
{
try {
Uri originalUri = filePath;
String pathsegment[] = originalUri.getLastPathSegment().split(":");
String id = pathsegment[0];
final String[] imageColumns = {MediaStore.Images.Media.DATA};
final String imageOrderBy = null;
Uri uri = getUri();
Cursor imageCursor = getActivity().getContentResolver().query(uri, imageColumns,
null, null, null);
if (imageCursor.moveToFirst()) {
int column_index_data = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
realPath = imageCursor.getString(column_index_data);
System.out.print("value" + realPath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
It works!.

How to get any File Path ,Name ,Extension from onActivityResult?

My Codes are:
1.
File file = new File(Environment.getExternalStorageDirectory(),"myFolder");
Log.d("path", file.toString());
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "*/*");
startActivityForResult(intent,0);
2.
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent FileReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, FileReturnedIntent);
How to get the file path,name,extension? (suppose files are in doc,pdf,csv format)
It return the file extention like pdf, doc .. etc
public static String getMimeType(Context context, Uri uri) {
String extension;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
}
return extension;
}
It returns you the real path where you get the file name. One friend use this way and it is really useful.
Get filename and path from URI from mediastore
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
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);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
You get file name from this
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
I am late but it can help others here is the solution.
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
String mime = cr.getType(uri);
you can use like this
#Override
public 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();
}
}
Once try as follows if the FileReturnedIntent contains File as extras
Bundle data1=FileReturnedIntent.getExtras();
File f=(File)data1.get(key);
String path=f.getAbsolutePath();
System.out.println("The file path along with extension is : "+path);
Hope this will helps you.
Nova day in Kotlin:
val myFile = File(data?.data!!.path)
you can put String Extra to intent using
intent.putExtra("path", your_path);
and get it in onActivityResult by
FileReturnedIntent.getStringExtra("path");

Pick photo from gallery in android 5.0

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

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