Yes. This is correct. You are basically starting an intent to get access to the native app. which in this case is the file system. The next would be a part of the onActivityResultData() which would then use the uri on the intent and get the contents of the file that has been selected.
Correct way to choose a file for open
-
09-03-2022 - |
Question
I am using this intent to open a chooser to pick up a file:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.parse(getExternalFilesDir(null).toString()), "*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
Intent chooser = Intent.createChooser(intent, "Choose File");
startActivityForResult(chooser, FILE_SELECT);
I don't fully understand it, but it works. I copied it from some example in the web
The result is an uri, but I find the processing of the uri, also copied from the example, too cumbersome
if(uri != null) {
if("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {"_data"};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if(cursor.moveToFirst()) {
return cursor.getString(column_index);
}
}
catch (Exception e) {}
} else if("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
}
Is this the simplest way to let the user pick a file and get its path?
Why do I need to check if the uri is "content"? I just want to open a text or zipped file the user chose in the intent.
Can I ignore the "content" check, just assume "file" and simply use uri.getPath()
?
Edit I: Is there a way to force choosing with uri scheme "file"?
Solution
OTHER TIPS
I'm wondering if Android isn't trying to push us away from file paths and towards Uris. Try something like:
InputStream inputStream=contentResolver.openInputStream(uri);
InputStreamReader file = new InputStreamReader(inputStream);
int size = file.read(text,0,mMaxLen);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow