app-dev
app-dev

Reputation: 348

How to save locally and retrieve files using Codename One and CN1 Filechooser?

I have studied the Files, Storage and Networking instructions on the Codename One website. I am trying to

  1. save files selected by the Codename One filechooser to the device (simulator, Android, iPhone)
  2. retrieve the files saved locally in whatever device they got saved on.

Here is the code I used:

 final Button getFileChooser = new Button("Get file chooser");
    getFileChooser.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {

            if (FileChooser.isAvailable()) {
                FileChooser.showOpenDialog(".pdf, .jpg, .jpeg, .png", e2-> {
                    String file = (String)e2.getSource();
                    if (file == null) {
                        hi.add("No file was selected");
                        hi.revalidate();
                    } else {
                        String extension = null;
                        if (file.lastIndexOf(".") > 0) {
                            extension = file.substring(file.lastIndexOf(".")+1);
                            ToastBar.showMessage("1: " + file, FontImage.MATERIAL_CHECK);
                            rawFilename.setText("raw: " + file);
                            //java.util.List<String> filepathParsed = StringUtil.tokenize(file, "[/.]");
                            StringBuilder hi = new StringBuilder(file);
                            if (file.startsWith("file://"))
                                hi.delete(0, 7);
                            int lastIndexPeriod = hi.toString().lastIndexOf(".");
                            Log.p(hi.toString());
                            String ext = hi.toString().substring(lastIndexPeriod);
                            String hmore = hi.toString().substring(0, lastIndexPeriod -1);

                            String hi2 = hmore +/* "/file" +*/ ext;/*hi;*/
                            Log.p("hi2 = " + hi2);
                            secondFilename.setText("2nd: " + hi2);
                            //secondFilename.setText((String)evt.getSource());
                            try {
                                saveFileToDevice(file, ext);
                            } catch (URISyntaxException e) {
                                e.getMessage();
                            }
                            //sendFileViaEmail(hi2, file);


                        } else {
                            ToastBar.showMessage("2: " + file + " " + extension, FontImage.MATERIAL_CHECK);
                        }
                    }
                    hi.revalidate();
                });
            }
        }
    });

 protected void saveFileToDevice(String hi, String ext) throws URISyntaxException{
    URI uri = new URI(hi);
    String path = uri.getPath();
    Log.p("uri path: " + uri.getPath() + " ; scheme: " + uri.getScheme());
    /*if (path.contains("..jpg")) {
        int indexLastPeriodBeforeExt = path.lastIndexOf(".");
        path = path.substring(0, indexLastPeriodBeforeExt) + path.substring(indexLastPeriodBeforeExt+ 1);
        Log.p("new path: " + path);

    }*/
    if (Display.getInstance().getPlatformName().equals("and"))
        path = "file://" +path;
    String home = FileSystemStorage.getInstance().getAppHomePath();
    char sep = FileSystemStorage.getInstance().getFileSystemSeparator();
    String userDir = home + sep + "myapp";
    /*if (hi.startsWith("file://")) {
        hi = hi.substring(7);
    }*/
    int index = hi.lastIndexOf("/");
    hi = hi.substring(index + 1);
    Log.p("hi after substring 7: " + hi);
    FileSystemStorage.getInstance().mkdir(userDir);
    String fPath = userDir + sep + hi ;
  /*  if (hi.contains("..jpg")) {
        int indexLastPeriodBeforeExt = hi.lastIndexOf(".");
        hi = hi.substring(0, indexLastPeriodBeforeExt) + hi.substring(indexLastPeriodBeforeExt+ 1);
        Log.p("new hi: " + hi);
    }*/

        Log.p("does it exist? " + FileSystemStorage.getInstance().exists(userDir));
        String imageFile = userDir + sep + hi;
         String[] roots = FileSystemStorage.getInstance().getRoots();
            if (roots.length > 0) {
                for (int i = 0; i < roots.length; i++)
                    Log.p("roots" + i + " " + roots[i]);
            }
            try {
                String[] files = FileSystemStorage.getInstance().listFiles(userDir);
                for (int i = 0; i < files.length; i++) {
                    Log.p(i + " " + files[i]);
                    //secondName = files[files.length-1];
                    Log.p("secondname: " + secondName);
                }
                sendFileViaEmail(imageFile, ".jpg");
            } catch (IOException e) {
                e.getMessage();
            }
        }

protected void sendFileViaEmail(String hi2, String file) {
    Message m = new Message("Test message");
    //m.getAttachments().put(file, "image/jpeg");
    m.setAttachment(hi2);
    m.setAttachmentMimeType(Message.MIME_IMAGE_JPG);
    //m.setMimeType(Message.MIME_IMAGE_JPG);
    //m.getAttachments().put(imageAttachmentUri, "image/png");
    Display.getInstance().sendMessage(new String[] {"[email protected]"}, "test message cn1", m);
}

I added the getFileChooser button to my Form after importing the cn1-filechooser library to my project and refreshed libs. The filechooser works -- I tried it on the simulator, Android device and iPhone.

My issue is here:

String file retrieves what looks like a URI. I tried to convert the URI to a File and when I run the following code to see that the files are stored I see them in my logs, although in a funny order, which I'm ok with.

 String[] files = FileSystemStorage.getInstance().listFiles(userDir);
            for (int i = 0; i < files.length; i++) {
                Log.p(i + " " + files[i]);
                //secondName = files[files.length-1];
                Log.p("secondname: " + secondName);
            }

How do retrieve a valid, uncorrupted version of this file from FileSystemStorage? Am I storing it wrong? Whenever I run the method to send the file via email, it opens Outlook (on my Desktop) but no files is attached? (I assume that the file is invalid/corrupted when trying to retrieve it from FileSytemStorage -- please help.) I hardcoded .jpg as MIME-type but only as a test; my goal is to be able to save/restore .pdf, .png, .jpg, and.jpeg files.

Thanks!

**EDIT: ** This seems to show that the file was actually saved to my app's storage. How do I stream the content of the file be copied/uploaded or emailed from my app?

Upvotes: 1

Views: 674

Answers (1)

Shai Almog
Shai Almog

Reputation: 52770

Mobile phones don't allow that. They don't have a file system like desktops have. So file chooser really launches a tool to help you pick a file from a different app, this file is then copied to your local app sandbox where you can get access to the content of the app.

Naturally this won't work for save as it would mean you could potentially corrupt a file within another application so you are restricted from writing to the directories of other applications installed or even knowing which applications are installed and where...

To transfer a file to a different app you have the share intent which you can use via the share button or the low level API's in display. This allows you to send an image to whatsapp or similar functionality that makes sense in a mobile phone.

Upvotes: 1

Related Questions