1
votes

I have a codenameone class which contains a method of upload a file for mobile app.I want to call that codenameone class method from my javascript function while user click on that upload button.

Below is my codenameone class method which is going to upload a file.

public void actionPerformed1(){ 
    if (FileChooser.isAvailable()) {
        FileChooser.showOpenDialog("image/*", e2-> {
            String file=null;
            if(e2!=null){
                file = (String)e2.getSource();
            }
            if (file == null) {
                hi.revalidate();
            } else {
                String extension = null;
                if (file.lastIndexOf(".") > 0) {
                    extension = file.substring(file.lastIndexOf(".")+1);
                }
                if ("txt".equals(extension)) {
                    FileSystemStorage fs = FileSystemStorage.getInstance();
                    try {
                        InputStream fis = fs.openInputStream(file);
                        hi.addComponent(new SpanLabel(Util.readToString(fis)));
                    } catch (Exception ex) {
                        Log.e(ex);
                    }
                } else {
                    hi.add("Selected file "+file);
                }
            }
            hi.revalidate();
        });
    }

Below is my html file where I will be using javascript to call codenameone actionPerformed1() method.

<pre>
    type="button" value="call method"    
    onClick = "document.FileChooserDemo.actionPerformed1()" 
</pre>

What can I do in javascript to call the codenameone method?

Thank you.

1
@Quentin Codename One is not a Java Applet. You are reading the code upside down this is an embedded mobile app... - Shai Almog

1 Answers

1
votes

Check out the JavaDocs for the javascript package specifically the section titled "Calling Java Methods from Javascript".

JSObject logger = (JSObject)ctx.get("{}");
logger.set("log", new JSFunction(){

    public void apply(JSObject self, Object[] args) {
        String msg = (String)args[0];
        Log.p("[Javascript Logger] "+msg);
    }

});

ctx.set("window.logger", logger);

Then from JavaScript this will work:

logger.log('This is a test message');