N V N V - 16 days ago 5
JSON Question

NullPointerException in Print Method

I have a method in a Restful WebService, which prints all the information of a

given record, based on its id.

When I test this method, I am getting a NullPointerException.

////////////////////////////My Code/////////////////////////

@SuppressWarnings("null")
@RequestMapping("print")
@ResponseBody
public ResponseEntity<Map<String, Object>> print(@RequestParam("id") Long id) {
Map<String, Object> mapPrint=null;
ResourceManage resourceManage = resourceManageService.findByIdwithowner(id);
Map<String, Object> params = new HashMap<String, Object>();
if (resourceManage.getDocumentOwner() != null && resourceManage.getDocumentOwner().getId() != null)
params.put("documentOwner", resourceManage.getDocumentOwner().getId());
else
params.put("documentOwner", null);
params.put("resId", id);
mapPrint.put("format", "pdf");
mapPrint.put("reportQuery", resourceManageService.generateReportQuery(params));
return new ResponseEntity<Map<String, Object>>(mapPrint, HttpStatus.OK);
}

Answer

You're getting an NPE, because you haven't instantiated mapPrint. Change

Map<String, Object> mapPrint=null;

to

Map<String, Object> mapPrint = new HashMap<>();
Comments