简体   繁体   中英

How to get PDF File Path In Android 11 and 12

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;
    }

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();
}

This one helps in my case on Android 11 hope anyone gets this helpful

    private String copyFile(Uri uri, String newDirName) {
    Uri returnUri = uri;

    Cursor returnCursor = this.getContentResolver().query(returnUri, new String[]{
            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE
    }, null, null, null);

    /*
     * Get the column indexes of the data in the Cursor,
     *     * move to the first row in the Cursor, get the data,
     *     * and display it.
     * */
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
    returnCursor.moveToFirst();
    String name = (returnCursor.getString(nameIndex));
    String size = (Long.toString(returnCursor.getLong(sizeIndex)));

    File output;
    if (!newDirName.equals("")) {
        File dir = new File(this.getFilesDir() + "/" + newDirName);
        if (!dir.exists()) {
            dir.mkdir();
        }
        output = new File(this.getFilesDir() + "/" + newDirName + "/" + name);
    } else {
        output = new File(this.getFilesDir() + "/" + name);
    }
    try {
        InputStream inputStream = this.getContentResolver().openInputStream(uri);
        FileOutputStream outputStream = new FileOutputStream(output);
        int read = 0;
        int bufferSize = 1024;
        final byte[] buffers = new byte[bufferSize];
        while ((read = inputStream.read(buffers)) != -1) {
            outputStream.write(buffers, 0, read);
        }

        inputStream.close();
        outputStream.close();

    } catch (Exception e) {

        Log.e("Exception", e.getMessage());
    }

    return output.getPath();
}

String newPath = copyFileToInternalStorage(uri, getResources().getString(R.string.app_name));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM