GPS and sensor data logger only works when connected to serial connection

Also, I am not sure how good my code is, I want to fix this section of code but I don't know how

First, you define what is wrong with it.
Then, you define what you want to do, instead.
Finally, you follow Captain Jean Luc Picard's direction, and "Make it so!".