How to Get Selected Xls File Path from Uri for Sdk 17 or Below for Android

How to get the Full file path from URI

Use:

String path = yourAndroidURI.uri.getPath() // "/mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

or

String path = yourAndroidURI.uri.toString() // "file:///mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

Implementing a File Picker in Android and copying the selected file to another location

STEP 1 - Use an Implicit Intent:

To choose a file from the device, you should use an implicit Intent

Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(chooseFile, PICKFILE_RESULT_CODE);

STEP 2 - Get the absolute file path:

To get the file path from a Uri, first, try using

Uri uri = data.getData();
String src = uri.getPath();

where data is the Intent returned in onActivityResult().

If that doesn't work, use the following method:

public String getPath(Uri uri) {

String path = null;
String[] projection = { MediaStore.Files.FileColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

if(cursor == null){
path = uri.getPath()
}
else{
cursor.moveToFirst();
int column_index = cursor.getColumnIndexOrThrow(projection[0]);
path = cursor.getString(column_index);
cursor.close();
}

return ((path == null || path.isEmpty()) ? (uri.getPath()) : path);
}

At least one of these two methods should get you the correct, full path.

STEP 3 - Copy the file:

What you want, I believe, is to copy a file from one location to another.

To do this, it is necessary to have the absolute file path of both the source and destination locations.

First, get the absolute file path using either my getPath() method or uri.getPath():

String src = getPath(uri);    /* Method defined above. */

or

Uri uri = data.getData();
String src = uri.getPath();

Then, create two File objects as follows:

File source = new File(src);
String filename = uri.getLastPathSegment();
File destination = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CustomFolder/" + filename);

where CustomFolder is the directory on your external drive where you want to copy the file.

Then use the following method to copy a file from one place to another:

private void copy(File source, File destination) {

FileChannel in = new FileInputStream(source).getChannel();
FileChannel out = new FileOutputStream(destination).getChannel();

try {
in.transferTo(0, in.size(), out);
} catch(Exception){
// post to log
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}

Try this. This should work.

Note: Vis-a-vis Lukas' answer - what he has done is use a method called openInputStream() that returns the content of a Uri, whether that Uri represents a file or a URL.

Another promising approach - the FileProvider:

There is one more way through which it is possible to get a file from another app. If an app shares its files through the FileProvider, then it is possible to get hold of a FileDescriptor object which holds specific information about this file.

To do this, use the following Intent:

Intent mRequestFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
mRequestFileIntent.setType("*/*");
startActivityForResult(mRequestFileIntent, 0);

and in your onActivityResult():

@Override
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
// Get the file's content URI from the incoming Intent
Uri returnUri = returnIntent.getData();
/*
* Try to open the file for "read" access using the
* returned URI. If the file isn't found, write to the
* error log and return.
*/
try {
/*
* Get the content resolver instance for this context, and use it
* to get a ParcelFileDescriptor for the file.
*/
mInputPFD = getContentResolver().openFileDescriptor(returnUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("MainActivity", "File not found.");
return;
}
// Get a regular file descriptor for the file
FileDescriptor fd = mInputPFD.getFileDescriptor();
...
}
}

where mInputPFD is a ParcelFileDescriptor.

References:

1. Common Intents - File Storage.

2. FileChannel.

3. FileProvider.

4. Requesting a Shared File.

How do I find the file path to my selected image using C# in Xamarin.Android?

The following worked for me:

private void AddImage_Click(object sender, EventArgs args)
{
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), 1);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == 1) && (resultCode == Result.Ok) && (data != null)
{
Android.Net.Uri uri = data.Data;
string path = GetPathToImage(uri);
Blob.UploadFileInBlob(path);
}
}
private string GetPathToImage(Android.Net.Uri uri)
{
ICursor cursor = ContentResolver.Query(uri, null, null, null, null);
cursor.MoveToFirst();
string document_id = cursor.GetString(0);
if (document_id.Contains(":"))
document_id = document_id.Split(':')[1];
cursor.Close();

cursor = ContentResolver.Query(
MediaStore.Images.Media.ExternalContentUri,
null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new string[] { document_id }, null);
cursor.MoveToFirst();
string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
cursor.Close();

return path;
}
public class Blob
{
public static async void UploadFileInBlob(string path)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("[string here]");
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("[Your container here]");
await container.CreateIfNotExistsAsync();
CloudBlockBlob blockBlob = container.GetBlockBlobReference("[Your Blob reference here]");
await blockBlob.UploadFromFileAsync(path);
}
}

Note: Be sure to grant READ_EXTERNAL_STORAGE under Required permissions in the Android Manifest through the project properties. Also, enable the Storage permission on your device for the app. Remember to add the file extension (e.g. jpg) to path or whatever variable you are using.

How to open specific folder in the storage using intent in android

This code may help you:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, YOUR_RESULT_CODE);

If you want to open a specific folder:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ File.separator + "myFolder" + File.separator), "file/*");
startActivityForResult(intent, YOUR_RESULT_CODE);


Related Topics



Leave a reply



Submit