Javascript.Current or UI.getCurrent returns null

I used the javascript to call the vaddin server function, but there is always a null error (java.lang.NullPointerException) for the first call

JavaScript.getCurrent()

, and after some seconds, i tried to call it for the second time, it works.
I have also tried to use

UI.getCurrent().getPage().getCurrent().getJavaScript()

, i have the same error.
Can you tell me how to resolve this problem, please?


In presenter
:

[code]
CustomerPlayerComponent player = new CustomerPlayerComponent();
view.getPanel().setContent(player);

[b]
CustomerComponent
[/b]
[/code]:

   [code]
 public CustomerPlayerComponent()
    {
        super();
        sample = new CustomLayout("playerlayout");
        setCompositionRoot(sample);
        Init();
        register();
    }

public void register()
    {
        [b]
JavaScript.getCurrent()
[/b].execute("alert('Hello')");
        JavaScript.getCurrent().addFunction("com.vaadin.customerComponent.save", new JavaScriptFunction()
        {
            /**
             *
             */
            private static final long    serialVersionUID    = 4119186268144783717L;

            @Override
            public void call(JsonArray arguments)
            {
                try
                {
                    System.out.println("call from client side");
                    System.out.println("arguments: " + arguments);
                    String message = arguments.getString(0);
                    // Double value = arguments.getNumber(1);
                    Notification.show("Message: " + message);
                }
                catch(Exception e)
                {
                    Notification.show("Error: " + e.getMessage());
                }
            }
        });
    }
[/code]

Are you executing the code outside of the HTTP request (= in another thread)? getCurrent is only available in the thread handling the HTTP request.

Hi,

Thank you for your reply, maybe, because for the first time i should download/prepare the object then i use the eventbus to notify when the component is ready, and for the second time, it use directly the cache to display.

In the presenter:

@Subscribe
    public void fileReadyResponse(final FileReadyResponseEvent event)
    {
        LOGGER.info(event.getClass().getSimpleName() + " received");
        if(event.isOk())
        {
            show(event.getFileName());
        }
    }

public void show(String filePath)
    {
        CustomerPlayerComponent player = new CustomerPlayerComponent(filePath);
        view.getPanel().setContent(player);
    }
Then in player, i registe the javascript function.

Maybe eventbus works in another thread like you said?

In this case how can i reslove this problem? Use something like access?

Thank you.

I found the problem, it’s related to the thread. because eventbus use another thread to do the action when there is a notification.