2
\$\begingroup\$

I have a listview of PrivateFile objects which contain the fileId (int), fileName (String) and the fileContent (byte []). In order to share the file, I currently save the file first, open it again, and then I share it. In my opinion this is really semi-professional. Is there a way wherein I can only share the file (content)/byte array without saving it before? Or can I improve my code in general?

privateDocs.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            try {
                PrivateFile selFile = (PrivateFile) arg0.getItemAtPosition(pos);

                File folder = new File(Environment.getExternalStorageDirectory() + "/myFolder");
                boolean success = true;
                if (!folder.exists()) {
                    success = folder.mkdir();
                }
                if (success) {
                    //safe file in order to open it later
                    File file = new File(folder.getAbsolutePath() + "/" + selFile.getFileName());
                    FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
                    fos.write(selFile.getFileContent());
                    fos.close();


                    Intent intentShareFile = new Intent(Intent.ACTION_SEND);

                    if(file.exists()) {
                        String newMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()));
                        intentShareFile.setType(newMimeType);
                        intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+file.getAbsolutePath()));
                        intentShareFile.putExtra(Intent.EXTRA_SUBJECT,
                                    "Sharing File...");
                        intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File...");

                        startActivity(Intent.createChooser(intentShareFile, "Share File"));
                    }

                } else {
                    throw new Exception("could not open folder");
                }
            } catch (Exception ex) {
                System.out.println("Err:" + ex.getMessage());
            }
            return true;
        }
    });
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.