tags:

views:

158

answers:

2

I want to keep a static string array to save variables passed from the client when it calls the server, and then to be able to access them from the client with a getter.

for some reason i can only get very basic type (int instead of Integer for instance) to work, everything else throws a null pointer exception.

here is a code snippet. (using GWT)

@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements AddElection
{

    //this seems to be throwing a NullPointerException:
    static String[] currentElections;
    static int index;

    public String electionServer(String input) {
        // save currently running elections 
        currentElections[index] = input;
        index = index + 1;

        // TODO: getcurrentElections

So. my question is, if i want to temporarily store a string array at the server side and be able to access it, how would i do this in google web toolkit? thanks!

+8  A: 

You havn't initialized your static array.

At least you have to do something like this:

static String[] currentElections = new String[ 100 ];

But it seems that your array could grow with time, so it's better to use a collection class instead:

static List<String > currentElections = new ArrayList<String >();

public String electionServer(String input) {
    // save currently running elections    
    currentElections.add( input );
}

But be careful if this method can be called simultaneously from several clients. Then you have to synchronize access like this:

static List<String > currentElections = 
    Collections.synchronizedList( new ArrayList<String >() );
tangens
aha! thanks very much - works like a charm!
flyingcrab
at risk of stoopid question, is that static List going to be persisted between RPC calls? if so where? on the Session? and does this violate the 'strive for statelessness' directive that is popular with people like Ray Ryan?
Michael Dausmann
All static members are stored with the class (not with the object). There they will stay until they are changed or your application terminates.
tangens
+2  A: 

Your array is not initialized. Btw, you should not use static variables in a multi threaded applications.

fastcodejava
.. unless they are applicationwide constants.
BalusC
whats a good way to get it to persist across multiple calls then?
flyingcrab
HttpSession data
matt b