This version saves a few words.
While walking toward my friend's house, I was so preoccupied I did not realize I was near the railway, until startled by a passing train.
And maybe it is enough to just say:
While walking toward my friend's house, I was startled by a passing train.
I like the simplicity of this version. If being preoccupied is really important to the narrative, then perhaps we should explain the source of the preoccupation?
But this is about style, not grammar.
Hope that helps.