user5913892
user5913892

Reputation: 123

Empty Arraylist JavaFX

I have a simple method like this:

public ArrayList<String> getImagefromGoogleUrl() {

        total = "http://www.google.it/search?q=&hl=it&gbv=2&tbm=isch&prmd=ivnsm&ei=5qW8Vua9Dsb-Pa36h7gH&start=0&sa=N";
        String stringa = "casa";
        total = total.replaceAll("q=", "q=" + stringa);

        resultList = new ArrayList<>();
        webview = new WebView();
        final WebEngine webengine = webview.getEngine();

        webengine.documentProperty().addListener((obs, oldDoc, newDoc) -> {
            if (newDoc != null) {
                nodeList = newDoc.getElementsByTagName("img");
                for (int i = 0; i < 10; i++) {
                    Element img = (Element) nodeList.item(i);
                    src = img.getAttribute("src");
                    resultList.add(src);
                    System.out.println("resultList è grande"+resultList.size());
                     System.out.println("resultlist vale"+resultList);
                    // System.out.println(src);
                }

            }
            else
                System.out.println("ciao");


        });
        webengine.load(total);
        System.out.println("resultList prima del return è grande"+resultList.size());
        return resultList;

    }

I make a query with the webengine Object where the string is total, then I put each path of the Images (the query is about image research) into an ArrayList. The elements are correct, but when I call the function getImagefromGoogleUrl() and I try to get the size , I get []. A clearer example:

ArrayList<String> prova = getImagefromGoogleUrl();

        if(prova.size()!=0)
        {
        System.out.println("prova size is"+prova.size());
        listaimmagini.addAll(prova);
        }

So in this way the arraylist prova is empty, I don't understand why?

Upvotes: 1

Views: 263

Answers (1)

wero
wero

Reputation: 32980

The Javadoc of WebEngine.load says:

Loads a Web page into this engine. This method starts asynchronous loading and returns immediately.

So you use the list when the callback which populates the list has not yet been called.


A solution would be to not return a list, but instead accept a Consumer<List> and call it once you have filled the list:

public void getImagefromGoogleUrl(Consumer<ArrayList<String>> consumer) {
    ...
    webengine.documentProperty().addListener((obs, oldDoc, newDoc) -> {
        ... fill list
        // no pass it to the consumer
        consumer.accept(resultList); 
    });
}

and use it like

getImagefromGoogleUrl(prova -> {
    if (prova.size() != 0) {
         System.out.println("prova size is" + prova.size());
         listaimmagini.addAll(prova);
    }
});

Upvotes: 2

Related Questions