The reason is that doInBackground is run in a background thread while onPreExectute onPostExecute are run in the UI-thread.
==> Url Connections should not be done from UI thread, (because it may freeze the UI while it is loading) that is why Android throws an NetworkOnMainThreadException whenever you try to do that.
==> This is the reason why you should establish network connections only asynchronously from the background thread not UI thread. That is why it only works in doInBackground.