Add null check to encode()

It is lacked null check.