0
votes

I have tried to use an instance of BufferReader to read a content of a web page but when running the app, it moves immediately to catch block when reaching this line:

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

Could you please tell me what is the problem? By the way, I have made a permmition to Internet connection in the mainifest file and there is no error registered in the Log cat! this is my java code:

        Thread thrd = new Thread( new Runnable() {          
        @Override
        public void run() {
            final Button btn = (Button) findViewById(R.id.btn_1);

            final TextView tv = (TextView) findViewById(R.id.tv_1);


            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    try {
                    URL url = null;
                    url = new URL("http://www.google.com/");
                    URLConnection conn = url.openConnection();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                    String Line = "";
                while( (Line= reader.readLine() )  != null){
                                           tv.append(Line);
                                          }
                                            catch (Exception e){
                    tv.append("There is a problem");  
                                            }
                }
            });

        }
    });
    thrd.start();   

    return true;
}
1
print the exception that you have catched! "there is a problem" is not a very helpful messagedonfuxx
can you pls replace tv.append("There is a problem"); with e.printStackTrace(); to see, what type of exception is thrown?Berťák

1 Answers

1
votes

have you tried logging the exception? something along the lines of

Log.d(TAG, "onClick", e); 

in your catch block.

With that said, you are probably getting a NetworkOnMainThreadException, because you are trying to access the network on the main thread. Because network calls are blocking, this will cause the UI to freeze - which is a very bad User Experience. All network calls should be done in a separate thread (be that a Service, AsyncTask, or a Thread).

see this SO answer for more information about the NetworkOnMainThreadException