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,

 

[code]

@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();
    }

}

[/code]

 

 

How to solve android.os.NetworkOnMainThreadException ?

 

 

Thread Class

[code]

@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();
}

[/code]

 

 

 

Using AsyncTask (Simple Async Task Example) 

[code]

@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();

}

[/code]

 

 

 

Using Thread Handler class (Simple Handler Thread Example)

[code]

@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);

}

[/code]

 

 

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.!

 

 

Add a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.