0

I want to fetch a file from the internal device storage in my app. The code for browsing through the internal storage is as follows

    public void select(){
        Intent intent = new Intent();
        //intent.setType("file/*");
        intent.setType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,86);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==86 && resultCode==RESULT_OK && data!=null){
            a=data.getData().getPath();
            //Log.e("uri",a);
            path.setText("File selected: "+data.getData().getLastPathSegment());
        }
        else{
            Toast.makeText(Template.this,"Please select a file",Toast.LENGTH_SHORT).show();
        }
    }

I am passing a as an input to the following function to fetch the data from the excel file

   public void convert(String uri){
        Log.e("Tag","uri");
        reference= FirebaseDatabase.getInstance().getReference();
        File file = new File(uri);
        try {
            Log.e("Try","Try");
            Workbook wb= Workbook.getWorkbook(file);
            Sheet s = wb.getSheet(0);
            int row=s.getRows();
            int col=s.getColumns();
            //for (int i=1;i<row;i++){
                for(int j=0;j<col;j++) {
                    Log.e("Tag",s.getCell(j,0).getContents());
                }
            //}

        } catch (IOException e) {
            Log.e("msg",e.getMessage());
            e.printStackTrace();
        } catch (BiffException e) {
            Log.e("msg",e.getMessage());
            e.printStackTrace();
        }

    }

This is the output I get:

/document/primary:Android/data/com.example.societyapp/files/Download/Maintenance Details.xlsx: open failed: ENOENT (No such file or directory)

  • A `Uri` is not a file. Use `getContentResolver().openInputStream(data.getData())` to get an `InputStream` on the content identified by the `Uri`. – CommonsWare Mar 21 '21 at 21:38
  • How do I get data from this InputStream? The file that I fetch after browsing is an excel sheet and I need it's contents. – Nandini Sharma Mar 22 '21 at 10:27
  • "How do I get data from this InputStream?" -- find some library that can parse an Excel sheet and accepts an `InputStream` as the source of data. If you can only find libraries that accept `File`, then use the `InputStream` to copy the content to a file that you control (e.g., in `getCacheDir()` on `Context`), then use the library with the resulting file. – CommonsWare Mar 22 '21 at 11:28
  • Thank you so much. This was great help. – Nandini Sharma Mar 22 '21 at 19:40

0 Answers0