I am new to GWT. I am writing a simple GWT program where I have a combo box (an instance of ValueListBox ) which lists the numbers from 1 to 12 representing the months in a year. My requirement is to set the current month to the combo on screen load. It works fine if I get the value of the current month from client side and set it to the combo. But, it does not work if I get the value of the current month from server side using RPC and set it to the combo. It always sets the initial value of the variable. In my case, it’s zero (currentMonth = 0 ) irrespective to the value returned from server. Can anyone please help me out how can I achieve this ?
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.text.shared.Renderer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ValueListBox;
public class Sample implements EntryPoint {
private int currentMonth = 0;
private final MyServiceAsync service = GWT.create(MyService.class);
public void onModuleLoad() {
setCurrentMonth();
final ValueListBox<Integer> monthCombo = new ValueListBox<Integer>(new Renderer<Integer>() {
@Override
public String render(Integer object) {
return String.valueOf(object);
}
@Override
public void render(Integer object, Appendable appendable) throws IOException {
if (object != null) {
String value = render(object);
appendable.append(value);
}
}
});
monthCombo.setValue(currentMonth);
monthCombo.setAcceptableValues(getMonthList());
RootPanel rootPanel = RootPanel.get();
rootPanel.add(monthCombo);
}
private List<Integer> getMonthList() {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 12; i++) {
list.add(i);
}
return list;
}
private void setCurrentMonth() {
service.getCurrentMonth(new AsyncCallback<Integer>() {
@Override
public void onSuccess(Integer month) {
currentMonth = month;
}
@Override
public void onFailure(Throwable caught) {
}
});
}
}
RPC calls in GWT are asynchronous. This means that when you call setCurrentMonth(), it will send the request to the server and return immediately. It will not wait for the response to be received before returning.
The consequence is that the remaining of the code in onModuleLoad() is likely to get executed before the onSuccess() method is called.
The right way to achieve what your trying to do is to update the ValueListBox from the onSuccess() method itself. This could be done by first making the ValueListBox an instance variable. Then in onSuccess() you could have: