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 ?
There is no file.
ACTION_OPEN_DOCUMENT
andACTION_GET_CONTENT
do not open a file. They open a document. That document might be a file. It might not. ThatUri
might point to:BLOB
column in a databaseYou don't.
If you wish to only accept files, integrate a file chooser library instead of using
ACTION_OPEN_DOCUMENT
orACTION_GET_CONTENT
.If you use
ACTION_GET_CONTENT
, and the scheme of theUri
that you get isfile
, thengetPath()
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
andopenInputStream()
, orDocumentFile.fromSingleUri()
, or similar techniques to work with theUri
.