How to get PDF File Path In Android 11 and 12

Viewed 2125

I tried much code for getting pdf path in android 11 or 12 but only working in android 10 or below devices. Can you please help me? I share my code of lines

Intent calling like this

Intent intent = new Intent();
            intent.setType("application/pdf");
            statusAdapter = "pdf";
            pos = position;
            intent.setAction(Intent.ACTION_GET_CONTENT);
            someActivityResultLauncher.launch(Intent.createChooser(intent, "Select PDF"));

someActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // There are no request codes
                        Intent data = result.getData();
                        if (data == null) {
                            //error
                            return;
                        }
                        try {
                            final Uri pdfUri= data.getData();
                            File pdfFile = new File(getPath(pdfUri));
                            long length = pdfFile.length();
                            length = length / 1024;
                            Toast.makeText(CreateSubEventActivity.this, "File Path : " + pdfFile.getPath() + ", File size : " + length + " KB", Toast.LENGTH_SHORT).show();
//                            uploadFile(imageFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(CreateSubEventActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
                        }
                    }
                });

getPath calling like this

public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) return null;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String s = cursor.getString(column_index);
        cursor.close();
        return s;
    }

2 Answers

If you want to access a File or want a file path from a Uri that was returned from MediaStore, I have got a library that handles all the exceptions you might get. This includes all files on the disk, internal and removable disk. When selecting a File from Dropbox, for example, the File will be copied to your applications directory where you have full access, the copied file path will then be returned.

Let me share my experience to fix this stuff after so reading all.

Get input stream from URI

final Uri pdfUri= data.getData();
getContentResolver().openInputStream(pdfUri)

then do your stuff with InputStream, like I have uploaded pdf using okHttp

try {

RequestBody pdffile = new RequestBody() {
    @Override public MediaType contentType() { return MediaType.parse("application/pdf"); }
    @Override public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
            source = Okio.source(inputStream);
            sink.writeAll(source);
        } finally {
            Util.closeQuietly(source);
        }
    }
    @Override
    public long contentLength() {
        try {
            return inputStream.available();
        } catch (IOException e) {
            return 0;
        }
    }
};

RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
        .addFormDataPart("file", "fname.pdf", pdffile)
        //.addFormDataPart("Documents", value) // uncomment if you want to send Json along with file
        .build();

Request request = new Request.Builder()
        .url(serverURL)
        .post(requestBody)
        .build();

OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS)
        .addInterceptor(chain -> {
            Request original = chain.request();
            Request.Builder builder = original.newBuilder().method(original.method(), original.body());
            builder.header("key", key);
            return chain.proceed(builder.build());
        })
        .build();

client.newCall(request).enqueue(new Callback() {

    @Override
    public void onFailure(final Call call, final IOException e) {
        // Handle the error
        setIsLoading(false);
        getNavigator().uploadIssue("Facing some issue to upload this file.");
    }

    @Override
    public void onResponse(final Call call, final Response response) throws IOException {
        setIsLoading(false);
        if (!response.isSuccessful()) {
            getNavigator().uploadIssue("Facing some issue to upload this file.");

        }else {
            // Upload successful
            getNavigator().uploadedSucessfully();
        }

    }
});

return true;
} catch (Exception ex) {
    // Handle the error
    ex.printStackTrace();
}
Related