Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File not found error after selecting a 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 am getting File Not Found Error when i check the file exist or not. Now after selecting the file my selected file Uri data.getData() is like

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

and the path when i parse using data.getData().getPath().toString() is 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 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) {
    }
}
like image 658
SHIDHIN.T.S Avatar asked Sep 29 '22 01:09

SHIDHIN.T.S


1 Answers

This is not the answer but a workaround.

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 this file's absolute path to your activity.

like image 136
Froyo Avatar answered Oct 31 '22 09:10

Froyo