Java – File not found error after selecting file in android

File not found error after selecting file in android… here is a solution to the problem.

File not found error after selecting file in android

I want to open a .pdf file in my Android app. Now I can browse the pdf file, and after browsing the file I get a file not found error I check if the file exists. Now after selecting the file, the file I selected Uri data.getData() looks like

content://com.android.externalstorage.documents/document/6333-6131:SHIDHIN.pdf

When I resolve with data.getData().getPath().toString() the path looks like

/

document/6333-6131:SHIDHIN.pdf Here is my code. Please help me.

// To Browse the file

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, PICK_FILE_REQUEST);

After selecting the file

//onActivityResult

public void onActivityResult(final int requestCode, int resultCode, Intent data) {
    try {
        switch (requestCode) {
            case PICK_FILE_REQUEST:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri fileUri = data.getData();
                        String path  = fileUri.getPath().toString();
                        File f = new File(path);
                        if (f.exists()) {
                            System.out.println("\n**** Uri :> "+fileUri.toString());
                            System.out.println("\n**** Path :> "+path.toString());
                            final Intent intent = new Intent(MainActivity.this, ViewPdf.class);
                            intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
                            startActivity(intent);
                        } else {
                            System.out.println("\n**** File Not Exist :> "+path);
                        }

} catch (Exception e) {
                        ShowDialog_Ok("Error", "Cannot Open File");
                    }
                }
                break;
        }
    } catch (Exception e) {
    }
}

Solution

This is not the answer, but the solution.

File file = new File("some_temp_path"); # you can also use app's internal cache to store the file
FileOutputStream fos = new FileOutputStream(file);

InputStream is = context.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[1024];
int len = 0;
try {
    len = is.read(buffer);
    while (len != -1) {
        fos.write(buffer, 0, len);
        len = is.read(buffer);
    }

fos.close();
} catch (IOException e) {
    e.printStackTrace();
}

Pass the absolute path to this file to your activity.

Related Problems and Solutions