I am trying to upload files to server from my application. The user is allowed to attach the file from his internal storage. But some how the path I get from a Nougat phone is different from the standard /storage/emulated/0/... . in few phones I get external_files/... and in others I get root_files/storage/999/.... . In this case I am not getting the right path of the file. How do we handle this scenario?
My code :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = data.getData().getPath();
File sourceFile = new File(fileFields.get(i).getFileName());
FileInputStream fileInputStream = new FileInputStream(sourceFile);
}
}
A Uri is not a file. getPath() is meaningless unless the scheme of the Uri happens to be file. That will not be very common on newer Android devices. Instead, the scheme will be content, and getPath() will be useless to you.
Instead, for both file and content Uri values, use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. This approach works all the way back to Android 1.0.
Related
In Android Studio:
This app must use COMTRADE files. The COMTRADE files are *.cfg *.dat and *.rio files. For example, (user.cfg, user.dat and user.rio). The main file is *.cfg file, so the user must browse by SAF to find *.cfg files, when the user select this file, the app must load other files ( *.dat and *.rio) automatically.
I can not use <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/> for android level 30
So I have to use Storage Access Framework, By below code the user browse *.cfg files and select a file like user.cfg
if(SDK_INT >= Build.VERSION_CODES.R)
{
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
Act.startActivityForResult(intent, 111);
}
else
{...}
Then SAF return URI of that user.cfg file, and the app does not have any URI of other files to load.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 111)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
try
{
Uri uri = null;
uri = data.getData();
InputStreamReader inputStreamReader = new InputStreamReader(getContentResolver().openInputStream(uri));
BufferedReader br = new BufferedReader(inputStreamReader);
// I want URI of user.dat how?
InputStreamReader inputStreamReader1 = new InputStreamReader(getContentResolver().openInputStream(uri1));
BufferedReader br1 = new BufferedReader(inputStreamReader1);
....
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
}
Please help me how can I do this? Thanks.
Please help me how can I do this?
You cannot do this, at least by means of using ACTION_OPEN_DOCUMENT, unless you ask the user to open each of your three documents in turn. Just because the user selected a .cfg file does not mean that you have any rights to any other files, including those adjacent to it.
You could try using ACTION_OPEN_DOCUMENT_TREE and let the user choose the document tree that contains your desired files. From there, you can:
Use DocumentFile.fromTreeUri() to get a DocumentFile representing the tree
Call listFiles() on that DocumentFile to get the direct contents of that tree, in the form of a list of DocumentFile objects
Call getName() on each of those to get their display names, then see which names have your desired file extensions and matching base names (foo.cfg and foo.rio and foo.dat)
For those that you want to use, call getUri() on the DocumentFile to get a Uri to use with ContentResolver and openInputStream() to read in the content
I am working on an app where I want to be able to export and import some data from the app, on a .txt file.
The minimum API of the app is 21.
The export part works well, but I am having trouble with the import part.
I open the file explorer :
butImportPatient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
startActivityForResult(intent, IMPORTPATIENT_ACTIVITY_REQUEST_CODE);
}
});
This looks like it is working.
But my onActivityResult doesn't work, I didn't find how I can get the file from the Uri.
For now, here is my code :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMPORTPATIENT_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
File file = new File(data.getData().getPath()) ;
String path = file.getAbsolutePath() ;
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n");
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this) ;
builder.setMessage(path)
.show() ;
}
}
It is a mix of multiple posts I saw here, but none seems to work.
I get this path :
/document/home:List.txt
It creates FileNotFoundException. How can I get the real path of the file ?
I didn't find how I can get the file from the Uri.
There is no file. ACTION_OPEN_DOCUMENT and ACTION_GET_CONTENT do not open a file. They open a document. That document might be a file. It might not.
That Uri might point to:
A local file on external storage
A local file on internal storage for the other app
A local file on removable storage
A local file that is encrypted and needs to be decrypted on the fly
A stream of bytes held in a BLOB column in a database
A piece of content that needs to be downloaded by the other app first
...and so on
How can I get the real path of the file ?
You don't.
If you wish to only accept files, integrate a file chooser library instead of using ACTION_OPEN_DOCUMENT or
ACTION_GET_CONTENT. Just bear in mind that filesystem access to external storage is limited on Android 10+.
If you use ACTION_GET_CONTENT, and the scheme of the Uri that you get is file, then getPath() will be a filesystem path.
Otherwise, you need to understand that you have no idea where the document is coming from, and stop thinking in terms of "real path of the file". Use ContentResolver and openInputStream() to make a copy of the content to some file that you control, then work with that file.
I'm trying to select pdf file from the device and upload them to the server. ACTION_GET_CONTENT is used to select pdf from the device.
sel_book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select PDF"), 1);
}
});
On activity result I get the Uri and save it as a String.
public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Uri uri = result.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
path = myFile.getAbsolutePath();
}
}
}
It results the path as, /document/primary:Download/Aptitude_2016_17.pdf. I need to use this to create a new file. File selectedFile = new File(selectedFilePath);. But it doesn't create File. selectedFile.isFile() returns false. I have no idea why is it. Please help me to solve this. Thanks in advance.
ACTION_GET_CONTENT is used to select pdf from the device.
This allows the user to select a piece of content. It does not have to be a file.
On activity result I get the Uri and save it as a String.
That is not how you use a Uri.
It results the path as, /document/primary:Download/Aptitude_2016_17.pdf.
That is not a filesystem path. That is a part of a Uri that has a content scheme. You do not get a file from ACTION_GET_CONTENT. You get a Uri that points to a piece of content. That Uri could point to anything that the user and the other app choose:
A file that you can access, via a Uri with a file scheme
A file, but one that you cannot access (e.g., on internal storage of another app)
The contents of a BLOB column in the database
A piece of content that needs to be downloaded
And so on
Use ContentResovler and openInputStream() to get a stream on whatever the content is. Either use that directly (with whatever you are using to upload this content), or use that stream to make your own file with a copy of that content, so that you have a file that you can use.
In my app I have this code allowing the user to select a file :
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent,1);
The user can select the .txt file from anywhere in his phone, even from google drive. When the file selection is done I retrieve a Uri object corresponding to the file. The problem is I can't use this Uri to read the file because it is not valid. Here is my code :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
File file = new File(uri.toString());
try{
InputStream inputStream = new FileInputStream(file);
int content;
while ((content = inputStream.read()) != -1) {
Log.d("===>", String.valueOf((char) content));
}
}catch (Exception e){
Log.d("===>", e.toString());
}
}
}
}
I always get a fileNotFoundException. My question is, is there a way to read the selected file (without knowing in advance the location it will come from). And if not, is there a way to copy the selected file in a folder from which I would easily get it ?
The problem is I can't use this Uri to read the file because it is not valid.
That is because a Uri is not a file.
is there a way to read the selected file (without knowing in advance the location it will come from)
The user did not select a file. The user selected a piece of content.
To consume the content represented by the Uri, call openInputStream() on a ContentResolver, passing in the Uri. This gives you an InputStream that you can use to read in the content.
In this other question
How to use the new SD card access API presented for Android 5.0 (Lollipop)?
It is explained how to use the new API to access the "external SDCard".
But, how can I know the actual directory returned in the result activity?
I mean in function
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode == RESULT_OK) {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
......
How can I get the actual path where "Uri treeUri" points?
Thanks,
Francis.
You can't get the absolute path because the Documents API is designed to abstract this from you.
However, the treeUri does contain the relative path to the file. Try examining the Uri using Uri#getPathSegments()
Use
FileUtil.getFullPathFromTreeUri(treeUri, this)
from
https://github.com/jeisfeld/Augendiagnose/blob/f24ddd7d3da4df94552ca0a9e658399602855a67/AugendiagnoseIdea/augendiagnoseLib/src/main/java/de/jeisfeld/augendiagnoselib/util/imagefile/FileUtil.java
to get the full path. Seperate the path using
final String[] seperated = treeUri.toString().split("\\/");
to get the current dir name.