Why does my code give NullPointerException error?

The initial post was not edited to the best of my knowledge. It was only edited after someone deleted the code and thereby changed the answer.