How to get file data from its uri in android - android

How to get file data from its uri in android.We tried following code but its giving filenot found exception.
uri2 = intent.getData();
uri = uri2.toString();
File objFile = new File(uri);
try {
InputStream data = new FileInputStream(objFile);
Log.d("data", data+"");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Please do help.
Thanks,
AA.

You can get the file path with the following piece of code :
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);
}
call the above function as follows :
String myFilePath = getPath(uri);
File objFile = new File(myFilePath);

Related

Recover real path from camera's picture

I'm taking picture from camera and saving in a public folder(Pictures/myFolder) and I'm storing the Uri from picture to reload to my views, but I need build a File with real path, but I cant recover the path and all the codes they find on the internet give me null pointer, how can i recover the real path?
Uri example:
content://media/content://br.com.technolog.darwinchecklist.fileprovider/darwin_checklist_images/DARWIN_20180827_114154_460340375.jpg/images/media
Method that does not work
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;
}
Ref: Get Real Path For Uri Android
getRealpathFromUri(Uri uri)
{
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor == null)
{ // Source is Dropbox or other similar local file path
result = contentURI.getPath();
}
else
{
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//String yourRealPath = cursor.getString(columnIndex);
path = cursor.getString(columnIndex);
}
cursor.close();
}
return path;
}
I'm using the following code to get the real path of a document from an Uri:
/**
* Retrieve filename from Uri
*
* #param uri Uri following the schemes: "file" or "content"
* #param contentResolver ContentResolver to resolve content scheme
*
* #return filename if operation succeded. Can be null.
*/
public static String getFileName(#NonNull final Uri uri, #NonNull final ContentResolver contentResolver) {
String filename = "";
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
filename = uri.getLastPathSegment();
} else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
try {
Cursor cursor = contentResolver.query(uri, null, null, null, null);
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
cursor.moveToFirst();
filename = cursor.getString(index);
cursor.close();
} catch (Exception e) {
Log.e(TAG, "Exception when retrieving file name: " + e.getMessage());
}
}
return filename;
}

How to get the date when an image was taken from MediaStore if I have the file path?

I know that I can retrieve the id of image using the following code:
String[] projection = { MediaStore.Images.Media._ID };
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { mediaFile.mediaFile().getAbsolutePath() };
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if(cursor!=null) {
if (cursor.moveToFirst()) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
}
cursor.close();
}
I wonder, if there is any possible way to MediaStore.Images.Media.DATA_TAKEN, MediaStore.Images.Media.LONGITUDE, andMediaStore.Images.Media.LATITUDE using the same approach?
Provided you have the file path, you can get the date this way:
File file = new File(filePath);
if(file.exists()) //Extra check, Just to validate the given path
{
Date lastModDate = new Date(file.lastModified());
Log.i("Dated : "+ lastModDate.toString());//Dispaly lastModDate. You can do/use it your own way
}
An alternative option to find this would be from the EXIF data of the image, if its available:
ExifInterface intf = null;
try
{
intf = new ExifInterface(path);
}
catch(IOException e)
{
e.printStackTrace();
}
if(intf != null)
{
String dateString = intf.getAttribute(ExifInterface.TAG_DATETIME);
Log.i("Dated : "+ dateString.toString()); //Dispaly dateString. You can do/use it your own way
}

cant get file path from URI

I am trying to open a intent that lets me choose a file. Im able to select a file but when I try creating a file with the Uri I got in the OnActivityResult method I get a file size of 0. I dont think Im getting the right file path.
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/TESTAPP4");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri data = Uri.fromFile(file);
String type = "*/*";
intent.setDataAndType(data, type);
startActivityForResult(intent, 12);
onActivityResult:
Uri u= data.getData();
File file = new File( u.getpath);
file.length() // give 0
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();
}
}
}
Get filename and path from URI from mediastore

file path return null always in lollipop android

this is my code when i'm getting image from internal storage (gallery).
In lollipop file path return always null.
if (requestCode == PICK_IMAGE) {
if(resultCode == RESULT_OK){
//image successfully picked
// launching upload activity
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
columnindex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
file_path = cursor.getString(columnindex);
Log.d(getClass().getName(), "file_path"+file_path);
fileUri = Uri.parse("file://" + file_path);
cursor.close();
launchUploadActivity(true, PICK_IMAGE);
}else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),"User cancelled image selection", Toast.LENGTH_SHORT).show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),"Sorry! failed to pick image", Toast.LENGTH_SHORT).show();
}
Thanx all,I found the solution.
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// 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();
setImageFromIntent(filePath);
Add permission to your manifest -
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
you have to define read permission, before read any content.
EDITED
Update your code -
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
columnindex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
file_path = cursor.getString(columnindex);
Log.d(getClass().getName(), "file_path"+file_path);
fileUri = Uri.parse("file://" + file_path);
cursor.close();
launchUploadActivity(true, PICK_IMAGE);
So here if any exception in getting data from cursor then it throws exception.
Lollipop decided to take another course with getting files from the system. (Some say it is from KitKat, but I haven't encountered it yet on KitKat). The code below is to get the filepath on lollipop
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(uri))
{
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type))
{
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
String filePath = getDataColumn(context, contentUri, selection, selectionArgs);
}
isMediaDocument:
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
getDataColumn:
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs)
{
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst())
{
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
If you still have problems, this is the full answer that checks for images, audio, video, files, etc.
///////////////////create file obj:
private File mFileTemp;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mFileTemp = new File(Environment.getExternalStorageDirectory(), InternalStorageContentProvider.TEMP_PHOTO_FILE_NAME);
}
else {
mFileTemp = new File(getFilesDir(), InternalStorageContentProvider.TEMP_PHOTO_FILE_NAME);
}
/////////////////// use in start activity for result
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
imagepath = mFileTemp.getPath();
} catch (Exception e) {
Log.e("TAG", "Error while creating temp file", e);
}
/////////////////
public static void copyStream(InputStream input, OutputStream output)
throws IOException
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1)
{
output.write(buffer, 0, bytesRead);
}
}
public void String(Uri file_uri){
String path = null;
Cursor returnCursor = getContext().getContentResolver().query(file_uri, null,
null, null, null);
if (returnCursor != null && returnCursor.moveToFirst()) {
//to get file name
int nameIndex =
returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
//string filename will get a filename which you have choosen
String fileName = returnCursor.getString(nameIndex);
//to get full path of image
path = returnCursor.getString(returnCursor.getColumnIndex(MediaStore.MediaColumns.DATA));
}
return path;
}

Android how to get the only uri of Media Store Image?

I'm trying to get the uri and after parse into path of MediaStore image.
I do this to get the uri:
Uri img_uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
And after with this function i convert uri in the path:
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();
}
}
}
But the result is that i have the path of the Media storage but with the first element.
For example: /mnt/sdcard/Pictures/Boat.jpg. But i want only /mnt/sdcard/Pictures/.
Please don't tell me to use join and split because isn't what i want.
Use this:
String path = getExternalFilesDir(null).getAbsolutePath();
to get the main directory in your app subfolder where you can put another directory, for example "Images" in this way:
String path = getExternalFilesDir(null).getAbsolutePath() + "/Images";
File folder = new File(path);
if (!folder.exists()) {
folder.mkdir();
}
So now with this:
String path = getExternalFilesDir(null).getAbsolutePath() + "/Images";
you can access to this folder without problems.

Categories

Resources