On /storage/emulated/0/Download directory, I'm not able to get read access of PDF file. How can I enable read access on it?
I'm using Android 13 Device, and android development in Kotlin.
Granted Read URI permission, but didn't get any luck.
On /storage/emulated/0/Download directory, I'm not able to get read access of PDF file. How can I enable read access on it?
I'm using Android 13 Device, and android development in Kotlin.
Granted Read URI permission, but didn't get any luck.
In this way you can get the URI of PDF
ActivityResultLauncher<String[]> filePickerLauncher= registerForActivityResult(new ActivityResultContracts.OpenDocument(),
result -> {
if (result != null) {
//DO SOMETHING WITH THE RESULT
}
});
Intent filePickerIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
filePickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
filePickerLauncher.launch(new String[] {"application/pdf"});
Update 1
If you want to upload file through retrofit you can use MultipartBody.Part
which is available in Retrofit
You can do it as follows:
private MultipartBody.Part createMultipartBody(File file) {
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
return MultipartBody.Part.createFormData(<Your key>, file.getName(), requestBody);
}
API interface
@Multipart
@POST(<Your endpoint here>)
Call<ResponseBody> yourMethod(@Part MultipartBody.Part file);
API calling:
Call<ResponseBody> apiCall = Client.getConverterClient().yourMethod(createMultipartBody(fileData));
apiCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
try {
if (response.code() == 200){
//HANDLE YOUR REST OF THE CODE HERE
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
//HANDLE ERROR HERE
}
});
Update 2
To get file path by using URI
you can use following snippet:
public static String getFilePath(Uri uri, Context context) {
Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
if (returnCursor == null) {
return null;
}
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read;
int maxBufferSize = 1024 * 1024;
int bytesAvailable = inputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
inputStream.close();
outputStream.close();
returnCursor.close();
} catch (Exception e) {
e.getLocalizedMessage();
}
return file.getPath();
}