Issue
public List<PostResponse> getAllPosts(Optional<Long> userId) {
List<Post> list;
if (userId.isPresent())
list = postRepository.findByUserId(userId.get());
list = postRepository.findAll();
return list.stream().map(p -> {
List<LikeResponse> likes = likeService.getAllLikesWithParam(Optional.ofNullable(null), Optional.of(p.getId()));
return new PostResponse(p, likes);}).collect(Collectors.toList());
}
public List<LikeResponse> getAllLikesWithParam(Optional<Long> userId, Optional<Long> postId) {
List<Like> list;
if(userId.isPresent() && postId.isPresent()) {
list = likeRepository.findByUserIdAndPostId(userId.get(), postId.get());
}else if(userId.isPresent()) {
list = likeRepository.findByUserId(userId.get());
}else if(postId.isPresent()) {
list = likeRepository.findByPostId(postId.get());
}else
list = likeRepository.findAll();
return list.stream().map(like -> new LikeResponse(like)).collect(Collectors.toList());
}
i get error in getAllPosts on this row Optional.ofNullable(null) error is: java.lang.NullPointerException: null
Solution
I can't tell just from the pasted code but it seems likely that likeService is null.
Also I would recomend using Optional.empty() instead of Optional.ofNullable(null) but that does not seem to be the cause of the problem here.
Answered By - L. Schilling
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)