1
I’m working with a Servlet however, this giving error java.lang.NullPointerException
when I use the object method DataVoting
. Follows the code:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DataVoting dataVoting;
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
request.getSession().invalidate();
dataVoting = new DataVoting();
if(request.getSession() == null){
request.getSession(true);
} else {
dataVoting = (DataVoting)request.getSession().getAttribute("DataVoting");
}
request.getSession().setAttribute("DataVoting", dataVoting);
Gson gson = new Gson();
String discipline = request.getParameter("discipline");
if(discipline != null) {
switch(discipline) {
case "Desenvolvimento de Sistema Web3":
if(dataVoting != null) {
dataVoting.Vote(1);
}
break;
case "Sistema Operacional":
dataVoting.Vote(2);
break;
case "Engenharia de Software":
dataVoting.Vote(3);
break;
case "Inglês Aplicado":
dataVoting.Vote(4);
break;
default:
System.out.println("Nenhum case!");
break;
}
}
request.getSession().setAttribute("DataVoting", dataVoting);
String json = gson.toJson(dataVoting);
response.getWriter().print(json);
}
Where the mistake happens?
– Maniero
In dataVoting.Vote(1);
– Deyvid Lira
It is impossible to give this error in this location, it only tries to execute this method if it is not
null
.– Maniero
So yesterday I showed the teacher, I even gave a system out inside the case and it worked the system out. Even letting everything commenting on the IDE point out the same error. Professor also failed to see reason for the error.
– Deyvid Lira
Code needs to be well done to always work. When it works in certain situations and others do not, the code needs to be rewritten. I’ll try to answer but I don’t know if it’ll help you since the past information doesn’t match.
– Maniero
Thank you, I just really wanted to understand this mistake, because I’ve never seen it that way. But as he said, he can show the return of a method in the system out, but he can’t do an operation that involves changing an attribute.
– Deyvid Lira