Tuesday, January 22, 2008

GWT - UIServiceAsync timing

I've been working a lot with GWT (google web toolkit), and have been using the user interface 'client side' , tying in to the back end. (server side). This introduces a few problems, especially with database calls. GWT translates Java into Javascript for you, but it doesn't try to generate javascript for the code you keep hidden away on the server side (thank goodness, especially since GWT currently only supports Java 1.4!)
So how does it know when the calls to the server side are complete?


Using AsyncCallbacks. These have onSuccess and onFailure methods you write yourself, which tell your UI side what to do when your server side calls have finished.


I have found that the timing of these prove to be a pain. Your client side code, like the tide and time, waits for no man. It will merrily march on, after you have made a call to get some data from the database for instance, and not care whether or not it has completed to run the next line. So you can't really depend on the feedback from the server side on the next line, your data might very well be null.
..or the line after that. or the next one.

So how do you make sure that darn query's output can be properly shown to the user?


the answer lies in the onSuccess method.
You make a structure to contain whatever you need on the UI side, and draw itself (as empty for now, or with a 'loading, please wait' message) to the screen.
Then, pass that container to the Async call. In the onSuccess method, you tell it to write the output to that container and draw itself again.


This way the user will always see something, and you won't get null Pointer exceptions.

Wednesday, January 2, 2008

comparing objects with nulls

When trying to test an object to see if it's null or not (for good error handling purposes), it's good to know: a null object's .equal method doesn't measure up to a null. ie, you can't do this:



String s = null;
String r = null;

possiblySetMyString(r);

if(s.equals(null)){
System.out.println("string not set");
throw new RuntimeException();
}else{
System.out.println(s);
}

public void possiblySetMyString(String t){
s = t;
}



Nope! That won't work. you can't check if a string 'equals' null with the object's .equals method , because it's going to try to compare various String parameters to a null. Instead, replace the s.equals(null) with s==null.
Note: use == to check for primatives (int, char, bool, null etc), and use .equals to compare two objects. If you're comparing two different types, better convert before comparing.