Android Image file path from URI - android

My Manifest activity code
<activity android:name="FileReceiver" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
My Activity code :
Intent i = getIntent();
String action = i.getAction();
if (action.equals(Intent.ACTION_SEND)) {
Uri imageUri = (Uri) i.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
Log.i("1234567", "URI : " + imageUri);
Log.i("123456", "path :" + imageUri.getPath());
File source = null;
source = new File(imageUri.getPath());
String fileNme = "/" + source.getName();
File destination = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path);
Log.i("123456", "destination path :" + destination);
try {
FileUtils.copyFile(source, destination);
} catch (IOException e) {
Log.i("123456", "IO Exception");
e.printStackTrace();
}
}
im getting exception
01-09 16:10:09.756: W/System.err(30225): java.io.FileNotFoundException: Source 'content:/media/external/images/media/127' does not exist
how do i get the path of the image when i receive an image from DCIM folder ?

/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
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();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
source:
Get/pick an image from Android's built-in Gallery app programmatically

I've got the same problem. Solved it using the following code:
public static String getPathFromURI(Context context, Uri contentUri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
DocumentsContract.isDocumentUri(context, contentUri)) {
return getPathForV19AndUp(context, contentUri);
} else {
return getPathForPreV19(context, contentUri);
}
}
private static String getPathForPreV19(Context context, Uri contentUri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
try {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
return cursor.getString(columnIndex);
} finally {
cursor.close();
}
}
return null;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private static String getPathForV19AndUp(Context context, Uri contentUri) {
String documentId = DocumentsContract.getDocumentId(contentUri);
String id = documentId.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
if (cursor != null) {
try {
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
return cursor.getString(columnIndex);
}
} finally {
cursor.close();
}
}
return null;
}

Related

Make telegram video call with specific contact with android programmatically

I want to make start a telegram video call from inside my android app, so I have decompiled the new telegram apk to find the following:
<intent-filter>
<action
android:name="android.intent.action.VIEW" />
<category
android:name="android.intent.category.DEFAULT" />
<data
android:mimeType="vnd.android.cursor.item/vnd.org.telegram.messenger.android.profile" />
<data
android:mimeType="vnd.android.cursor.item/vnd.org.telegram.messenger.android.call" />
<data
android:mimeType="vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video" />
</intent-filter>
There is something related to call.video, but I don't know how to use this data element in the code, my only try was to do the following:
Intent telegram = new Intent(Intent.ACTION_VIEW ,
Uri.parse("https://telegram.me/"+contact));
startActivity(telegram);
I expect something like telegram.setType("video"); or telegram.setType("vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video").
Is it possible at the end ?
Thanks in advance
You need to use URI contactID with mimeType which is "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video". Looking first contactID by number phone:
private String getContactIdByPhoneNumber(String phoneNumber) {
ContentResolver contentResolver = getContentResolver();
String contactId = null;
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = new String[]{ContactsContract.PhoneLookup._ID};
Cursor cursor = contentResolver.query(uri, projection, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
cursor.close();
}
return contactId;
}
then use this contactID and mimeType to find URI:
private Uri getUriFromPhoneNumber(String phoneNumber) {
Uri uri = null;
String contactId = getContactIdByPhoneNumber(phoneNumber);
String mimeTypeTelegram = "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video";
Cursor cursorTelegram = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[]{contactId, mimeTypeTelegram}, null);
if (cursorTelegram != null) {
while (cursorTelegram.moveToNext()) {
String id = cursorTelegram.getString(cursorTelegram.getColumnIndexOrThrow(ContactsContract.Data._ID));
if (!TextUtils.isEmpty(id)) {
uri = Uri.parse(ContactsContract.Data.CONTENT_URI + "/" + id);
break;
}
}
cursorTelegram.close();
}
return uri;
}
after which use Intent.ACTION_VIEW:
public void videoCallToTelegramContact(String phoneNumber) {
Uri uri = getUriFromPhoneNumber(phoneNumber);
Log.d(TAG, uri + "");
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
It would be nice to add a check for the installed 'Telegram', as well as whether the user has allowed the video call.

How to open pdf in my android app from file manager in android pie

Not working in Android-Pie only
Not able to get file path from intent
result of intent.getData().getPath() -> /2/19301
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_VIEW.equals(action) && type.endsWith("pdf")) {
Uri file_uri = intent.getData();
if (file_uri != null) {
Log.d("file_path",""+file_uri.getPath());
startActivity(new Intent(this, ReaderActivity.class).putExtra("file_path", file_uri.getPath()));
} else {
Log.e("Pdf_Viewer", "File Not Found");
}
working on old devices
readstorage permission provided and granted
file provider already added
<activity android:name=".PdfViewer" android:label="#string/app_name">
<intent-filter tools:ignore="AppLinkUrlError">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/pdf" />
</intent-filter>
</activity>
just update your menifest
To get file path in Android 9(Pie) as follow
in side onActivityResults - File originalFile = new File(FileUtils.getRealPath(getActivity(), uri));
Create new FileUtils as below
public class FileUtils {
public static String getRealPath(Context context, Uri fileUri) {
String realPath;
// SDK < API11
if (Build.VERSION.SDK_INT < 11) {
realPath = FileUtils.getRealPathFromURI_BelowAPI11(context, fileUri);
}
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19) {
realPath = FileUtils.getRealPathFromURI_API11to18(context, fileUri);
}
// SDK > 19 (Android 4.4) and up
else {
realPath = FileUtils.getRealPathFromURI_API19(context, fileUri);
}
return realPath;
}
#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);
cursor.close();
}
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 = 0;
String result = "";
if (cursor != null) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
cursor.close();
return result;
}
return result;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// This is for checking Main Memory
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return Environment.getExternalStorageDirectory() + "/";
}
// This is for checking SD Card
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
String fileName = getFilePath(context, uri);
if (fileName != null) {
return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
}
String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
id = id.replaceFirst("raw:", "");
File file = new File(id);
if (file.exists())
return id;
}
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (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.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public 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 index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static String getFilePath(Context context, Uri uri) {
Cursor cursor = null;
final String[] projection = {
MediaStore.MediaColumns.DISPLAY_NAME
};
try {
cursor = context.getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
You have to add FileProvider inside Manifest.xml like below
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="<YOUR PACKAGE NAME>.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
Then Go to you java file and create below method and pass originalFile in this method
private void openPDF(File fileName) {
try {
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = fileName.getName().substring(fileName.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(getContext(), "<YOUR PACKAGE NAME>.fileProvider", fileName);
intent.setDataAndType(contentUri, type);
} else {
intent.setDataAndType(Uri.fromFile(fileName), type);
}
startActivity(intent);
} catch (ActivityNotFoundException anfe) {
Toast.makeText(getContext(), "No activity found to open this attachment.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
This will help you to open PDF file

How to handle different type of content uri

I want to get image URI from another app like a gallery, google drive, whats app etc
I have registered following intent filter :
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*" />
</intent-filter>
and to get the actual path
if (_uri != null && "content".equals(_uri.getScheme())) {
Cursor cursor = this.getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();
} else {
filePath = _uri.getPath();
}
with this, I am able to see my app from gallery whats app. From gallery, I am able to get image path URI but when I am trying to share from other apps like whatsapp or google drive its give me null
how to get path from different types of app
Check Out this may help
In the manifest :
<activity android:name=".ui.MyActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
And on Activity
void onCreate (Bundle savedInstanceState) {
...
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
...
}
For more info check : https://developer.android.com/training/sharing/receive#java
After getting the contentURI, you can use the following method to get the actual Uri using following method.
// You can use call the method from your activity like this.
String path = getPath(this,contentURI);
//This the method to get the actual path from the uri
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
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.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return uri.getPath();
}
/**
* Method to check if the uri is external storage document
*
* #param uri uri
* #return true if the uri authority is of external storage
*/
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* Method to download the document
*
* #param uri uri
* #return true if uri is of type download documents
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri.
*/
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
final String column = "_data";
final String[] projection = {
column
};
try (Cursor 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);
}
}
return null;
}
// isGoogleDriveUri method
private static boolean isGoogleDriveUri(Uri uri) {
return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
}
//getDriveFilePath method
private static String getDriveFilePath(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getCacheDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}
//For whatsapp u can use:
// whatsapp returns the uri in this particular way - content://com.whatsapp.provider.media/item/xxxxx
InputStream is = getContentResolver().openInputStream(uri);
Now u have to get the file path using this input stream. Then u have to read from input stream.
U may have to add it in the last if else block like:-
if ("content".equalsIgnoreCase(uri.getScheme())) {
String path = "";
try{
path = getDataColumn(context, uri, null, null);
}catch (Exception e){
try {
InputStream is = context.getContentResolver().openInputStream(uri);
//TODO: read this input stream to get data
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
return path;
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
String path = "";
try{
path = uri.getPath();
}catch (Exception e){
try {
InputStream is = context.getContentResolver().openInputStream(uri);
//TODO: read this input stream to get data
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
return path;
}

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

how to get Real Path from Uri?

I would like to upload file to server. So I use a file chooser. But I have a problem with some application to get the real path from uri. the case if the content is a v
ideo, audio or image or if I can get the path directly i have no problem. the methode imlemented are :
public String getRealAudioPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Audio.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader(
this,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
and it is the some for image and video. but my problem is when content is in this forme:
content://com.dataviz.dxtg.documentprovider/document/file%3A%2F%2F%2Fmnt%2Fsdcard%2FDownload%2Arbres.png
I tried the method
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) {
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
So how to get the real path from URi and if there is an other content type .
to get my real path is given below:
//Uri return from external activity
orgUri = data.getData();
text1.setText("fichier à envoyer " + orgUri.toString() + "\n");
// imagepath = orgUri.toString() ;
//path converted from Uri
//convertedPath = orgUri.getPath();
if(orgUri.toString().contains(IMAGEMEDIA)){
convertedPath = getRealPathFromURI(orgUri);
} else if(orgUri.toString().contains(AUDIOMEDIA)){
convertedPath = getRealAudioPathFromURI(orgUri);
}
else if(orgUri.toString().contains(VIDEOMEDIA)){
convertedPath = getRealvideoPathFromURI(orgUri);
}else {
if(orgUri.toString().contains("content")){
convertedPath = getFilePathFromContentUri(orgUri,
getApplicationContext().getContentResolver());
} else {
convertedPath = orgUri.getPath();
}
}
try this one
Uri selectedFile = data.getData();
String path = selectedFile.getPath();
it works for me.
if it is not than let me inform i have another way too
This works for me...
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >=
Build.VERSION_CODES.KITKAT;
Log.i("URI",uri+"");
String result = uri+"";
// DocumentProvider
// if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isKitKat && (result.contains("media.documents"))) {
String[] ary = result.split("/");
int length = ary.length;
String imgary = ary[length-1];
final String[] dat = imgary.split("%3A");
final String docId = dat[1];
final String type = dat[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
} else if ("audio".equals(type)) {
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
dat[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
else
if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public 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;
}
It is a problem of decode. So the Solution is to add decode to the method. as given below:
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) throws UnsupportedEncodingException {
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
String result = java.net.URLDecoder.decode(filePath, "UTF-8");
return result;
}
my onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
//image.setImageBitmap(null);
//Uri return from external activity
orgUri = data.getData();
text1.setText("fichier à envoyer " + orgUri.toString() + "\n");
// imagepath = orgUri.toString() ;
//path converted from Uri
//convertedPath = orgUri.getPath();
if(orgUri.toString().contains(IMAGEMEDIA)){
convertedPath = getRealPathFromURI(orgUri);
} else if(orgUri.toString().contains(AUDIOMEDIA)){
convertedPath = getRealAudioPathFromURI(orgUri);
}
else if(orgUri.toString().contains(VIDEOMEDIA)){
convertedPath = getRealvideoPathFromURI(orgUri);
}else {
if(orgUri.toString().contains("content")){
try {
convertedPath = getFilePathFromContentUri(orgUri,
getApplicationContext().getContentResolver());
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
convertedPath = orgUri.getPath();
}
}
// text2.setText("Real Path: " + convertedPath + "\n");
imagepath = convertedPath;
uriFromPath = Uri.fromFile(new File(convertedPath));
}
}

Categories

Resources