Search Posts

Solve Android.OS.NetworkOnMainThreadException


Working with Xamarin.Android (or Xamarin.Forms with Android) you might encounter this error when making HTTP/REST calls to an API, even if you think your making the call async. So what’s up with that?

The Culprit

What can commonly happen is you got some nested async call like this (simplified):

While Login will begin to execute async and the nested call to Authenticate (signature async Task<TokenResponse>) will also do so the assignment to this.TokenResponse (a public property with RaisePropertyChanged) will not.

So Android takes offense with this and throws the Android.OS.NetworkOnMainThreadException which might crash your app.

The Workaround

To get around these type of issues, make sure that stuff that normally happen on the main thread – i.e. related to UI – are in fact invoked on main thread. In the case of Xamarin.Forms, its done using the Device class:

Happy coding

%d bloggers like this: