List does not contain objects added in anonymous inner class.

Hi all, I am having an anonymous inner class in which I am adding objects to a list which is declared outside the inner class. After the control comes out of the inner class the list size is again zero. Can anyone explain why is this so?

Love all, trust a few, do wrong to none.

Joanne Neal

Rancher

Posts: 3742

16

posted 3 years ago

1

Have you checked that your onSuccess method is actually being called ?
If it is, have you checked that the list that is passed to it actually contains any objects ?
Your onFailure method is empty ? How do you know if an exception is being thrown or not ?

Joanne Neal wrote:Have you checked that your onSuccess method is actually being called ?
If it is, have you checked that the list that is passed to it actually contains any objects ?
Your onFailure method is empty ? How do you know if an exception is being thrown or not ?

I used print statements, success method is being called and the list contents are printed in my console.

That's a GWT asynchronous callback. The "asynchronous" part here is key - it means that the code in the onSuccess / onFailure methods will be executed at some unspecified time in the future.

What happens with that code is as follows:
1) The contacts List is created.
2) An HTTP call is made to the listContacts method of the rpcService.
3a) The contacts list is printed.
4a) The contacts list is returned.

3b) The rpcService call returns a List<Contact>.
4b) The contacts list is filled with the contents of this List.

The problem is, you don't know when steps 3b and 4b occur. They could occur almost immediately, or they could occur a minute later if the network latency is high.

So unfortunately, your design will not work the way you want it. That's something you will run into not just with GWT but with all frameworks that use asynchronous callbacks (like ActionListeners in AWT / Swing).

I had to deal with the same issue, and I solved it by adding another callback. This callback was provided by the code that called the method, and the asynchronous method simply calls the callback method.