This exception occurs when you write network code on main thread (UI thread). It will throw following exception
android.os.NetworkOnMainThreadException
Solution:-
Write your network part code on background threat (AsyncTask)
class void extends AsyncTask<String, Void, String> { private Exception exception; protected String doInBackground(String... urls) { try { // network part // Don't use user interface here return null; } catch (Exception e) { this.exception = e; return null; } } protected void onPostExecute(String str) { // TODO: check this.exception // TODO: show output on user interface } }
For more detail check following links:
How to use background thread in android. Android thread example