I am using a file chooser to pick a WORD file downloaded from GMail, it causes the app crashed.Here's my code segment:
== file chooser code ==
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.addCategory(Intent.CATEGORY_OPENABLE);
//sets the select file to all types of files
String [] mimeTypes = {"application/pdf", "application/msword",
"application/vnd.openxmlformats
officedocument.wordprocessingml.document"};
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
activity.startActivityForResult(Intent.createChooser(intent, "Select
File"), PICK_FILE_REQUEST);
== onActivityResult ==
Uri selectedFileUri = data.getData();
String selectedFilePath = FilePath.getPath(getActivity(),
selectedFileUri);
== FilePath.getPath() ==
...
// DownloadsProvider
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);
== getDataColumn() ==
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;
}
The selectedFilePath has this value: content://com.android.providers.downloads.documents/document/164, the contentUri in FilePath.getPath() also has this value. When it goes in getDataColumn() method, the cursor is null after executing "query()".
Tried those: 1) If I put the same WORD file direct to the "Download" folder and pick it from "Downloads" link from the file chooser, I have no issue. It seems that somehow going through GMail and downloading from GMail causes problem. 2) File still downloaded from GMail and in Download folder, if I pick it through Internal storage->Download (i.e, absolute path), it works since the code goes through different flow (which is not shown above).
I am wondering where I missed in the code to handle the file downloaded from GMail?
Thanks in advance!
The Phone is Galaxy S9, android 9.
After some search and experiment, it ends up retrieving file name and content from InputStream instead of trying to get the path of the file. Here's the code segment:
1) get file details:
Here's the FileDetail.java:
In FilePath.java:
2) get the file content:
I found those codes from internet and didn't keep track of where they are. With Filename & filesize in FileDetail.java and the file content in "filecontent" byte arrays, I have all information I need now.