1

I have an HTML form that calls a Java servlet and the form contains 20 checkboxes (e.g. with names of c1, c2, c3...c20).

I'm trying to capture the value of those checkboxes in a java boolean array cbox.

The following code...

int ii=0;
boolean cbox[] = new boolean[20];
for (ii=0; ii<20; ii++)
   cbox[ii] = (req.getParameter("c"+String.valueOf((int)(ii+1))).equals("on"))?true:false;

gives a java.lang.NullPointerException.

But, I don't get a run time error if I were to change it to (e.g. remove ii in valueOf):

   cbox[ii] = (req.getParameter("c"+String.valueOf((int)(1))).equals("on"))?true:false;

Of course, that doesn't get me where I want. I must be making a silly mistake somewhere but I can't spot it. Does anyone see it?

user46688
  • 733
  • 3
  • 11
  • 29

2 Answers2

2

A NullPointerException occur when you try to reference an Object that is not initialized (null).

Looking at your code, there are two possibilities :

  • req is null req.getParameter.
  • The parameter you are trying to retrieve does not exists hence is null req.getParameter("c"+String.valueOf((int)(ii+1))).

By the way, if your returned parameter is already a boolean, there is no need to check the value of it and return true or false as it value is already true or false. You can simplify it to :

cbox[ii] = (req.getParameter("c"+String.valueOf((int)(ii+1))).equals("on"));

Edit : To answer to your comment, you could validate if the parameter exist easily :

String param = req.getParameter("c" + String.valueOf(ii + 1));
cbox[ii] = "on".equals(param);

To be even more secure, I would also check req to make sure it is not null.

if(req != null)
{
    String param = req.getParameter("c" + String.valueOf((ii + 1));
    cbox[ii] = "on".equals(param);
}

Notice that I removed the cast (int)ii + 1 as the expression is already of type integer.

Also, if ii is only to be used as an iterator id, you can declare it directly in the loop, so instead of doing this :

int ii = 0;
for(ii = 0; ii < 20; ii++)

You can directly write for(int ii = 0; ii < 20; ii++)

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
1

The problem here is in servlet, you will receive on as default value for html selected checkbox else null. Since all checkboxes are not checked you get NPE. Try this code snippet:

boolean[] cbox = new boolean[20];
for(int i = 0; cbox.length > i; i++) {
   cbox[i] = null != req.getParameter("c" + (1 + i));//if not null then true else false
}

You can also go with other option:

in your html/jsp create checkboxes with same name but different value:

<input type="checkbox" name="cbox" value="1"/>
<input type="checkbox" name="cbox" value="2"/>
...
<input type="checkbox" name="cbox" value="20"/>

in servlet you can fetch all checked boxes with single line:

String[] cbox = req.getParameterValues("cbox");

Here you won't get on as value, its gona be 1, 2 and so on as per selection. Only checked boxes you will get here.