Did you get android.os.NetworkOnMainThreadException ?

Hello guys,

Today i would like to explain about an exception that occurs very often for Android Developers.  I can imagine the situation, if you are a newbie or seasonal android developer you would definitely encounter android.os.NetworkOnMainThreadException for sure.

 

This exception is predominantly thrown when an application attempts to perform a networking operation on its main thread.

Never ever forget that Main thread is the UI thread and you cannot do a non-UI operations in the main thread whatsoever.  It will definitely block the user Interaction.

 

If you try to execute the following code, The exception will be thrown,

 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    try {
        URL page = new URL("https://www.google.com");
        StringBuffer text = new StringBuffer();
        HttpURLConnection conn = (HttpURLConnection) page.openConnection();
        conn.connect();
        InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
        BufferedReader buff = new BufferedReader(in);
        String line;
        while ( (line =  buff.readLine()) != null) {
            text.append(line + "\n");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

 

 

How to solve android.os.NetworkOnMainThreadException ?

 

 

Thread Class

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                URL page = new URL("https://www.google.com");
                StringBuffer text = new StringBuffer();
                HttpURLConnection conn = (HttpURLConnection) page.openConnection();
                conn.connect();
                InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
                BufferedReader buff = new BufferedReader(in);
                String line;
                while ( (line =  buff.readLine()) != null) {
                    text.append(line + "\n");
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });

    thread.start();
}

 

 

 

Using AsyncTask (Simple Async Task Example) 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    class SimpleTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            StringBuffer text = new StringBuffer();
            try {
                URL page = new URL("https://www.google.com");

                HttpURLConnection conn = (HttpURLConnection) page.openConnection();
                conn.connect();
                InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
                BufferedReader buff = new BufferedReader(in);
                String line;
                while ( (line =  buff.readLine()) != null) {
                    text.append(line + "\n");
                }

                System.out.println("text is " + text);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return text.toString();
        }

        @Override
        protected void onPostExecute(String text) {
            super.onPostExecute(text);
            System.out.println("text is " + text);
        }

    };
    SimpleTask simpleTask = new SimpleTask();
    simpleTask.execute();

}

 

 

 

Using Thread Handler class (Simple Handler Thread Example)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    HandlerThread handlerThread = new HandlerThread("threadname");
    handlerThread.start();
    Handler mainHandler = new Handler(handlerThread.getLooper());

    Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            StringBuffer text = new StringBuffer();
            try {
                URL page = new URL("https://www.google.com");

                HttpURLConnection conn = (HttpURLConnection) page.openConnection();
                conn.connect();
                InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
                BufferedReader buff = new BufferedReader(in);
                String line;
                while ( (line =  buff.readLine()) != null) {
                    text.append(line + "\n");
                }

                System.out.println("text is " + text);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };

    mainHandler.post(myRunnable);

}

 

 

There are other ways too…! You can use Latest Network libraries such as Retrofit, ReactiveJava, Volley and etc… We will look at them in separate post.

 

Cheers.!

 

 

About Zumry

Zumry Mohamed

Self Taught iOS & Android Mobile Application Developer.

Article written by zumrywahid

Self Taught iOS & Android Mobile Application Developer.

Be the first to comment

Leave a Reply

Your email address will not be published. Required fields are marked *