Try failing when reading content from URL

55 Views Asked by At

So I have a class with the following:

class NetworkRequest extends AsyncTask<String, StringBuilder, String> {

     @Override
    public String doInBackground(String... urls) {

        try
        {
            URL url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream inputStream = url.openStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuilder stringBuilder = new StringBuilder();
            int cp;
            while ((cp = bufferedReader.read()) != -1)
            {
                stringBuilder.append((char) cp);
            }

            return stringBuilder.toString();
        }
        catch(Exception ex)
        {
            return null;
        }
    }

    public void onPostExecute(String string)
    {

    }
}

And it is being called here:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mediated);
    TextView welcome_txt = (TextView) findViewById(R.id.test_view);
    new NetworkRequest().execute("https://graph.facebook.com/me");
    NetworkRequest networkRequest = new NetworkRequest();
    String string = networkRequest.doInBackground();
    test_view.setText(string);
}

When this is executed I am returning with "nothing" which explains it is falling in the catch statement of the doInBackground method, I get an exception of:

android.os.NetworkOnMainThreadException

Does anyone understand what I am doing wrong?

2

There are 2 best solutions below

2
On

Direct Reason for the Exception is that you shouldn't run Networking on your main thread, instead, run it in a background thread and only update your UI from it.

One way to do that is AsyncTask (as you are trying), another way is to use a library such as Volley or retrofit which take care of the background threading for you.

0
On

You should not directly invoke the doInBackground method of AsyncTask instead you should call execute method on your AsyncTask object which will take care executing the network request in the background thread. developer.android.com/reference/android/os/AsyncTask.html