0

So i am following the lynda course on android development and after following the URL connection tutorial, for some reason the instructor's code produces results but mine does not. here are the files that i have

Main.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main extends Activity {



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

     final EditText et = (EditText) findViewById(R.id.editText1);
     Button pressMe= (Button) findViewById(R.id.button1);
     final TextView tv = (TextView) findViewById(R.id.textView1);

    pressMe.setOnClickListener(new OnClickListener(){


        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try{

                URL url = null;
                url = new URL(et.getText().toString());
                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){

                    }



        }







    });


}
}

i have checked my code and compared it with the instructors. i have also checked online to see if the URL connection method is still valid and after research it is still valid. I have dont another tutorial using HTTpClient and i have gotten results from that. However for learning purposes i would like to see if URL connection works. I do hae the internet permission enbaled in my Android_manifest file. Thank you for the help.

Ali Aslam
  • 115
  • 1
  • 9
  • 2
    You're probably catching and ignoring an exception. – David Conrad Jan 05 '15 at 04:03
  • 4
    I would guess that your empty `catch` block is hiding a [`NetworkOnMainThreadException`](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception). – Mike M. Jan 05 '15 at 04:08
  • 1
    What @DavidConrad said. It is **never** a good idea to catch an exception and do absolutely nothing with it. Log it, print a message to the user, do **something** – codeMagic Jan 05 '15 at 04:08
  • 1
    David Conrad is right. You're trying to run `URLConnection` in the GUI thread, which Android does not allow. Your exception catching block is empty, you should put something in there like adding an entry to the log like `Log.e("TAG", "Exception: " + e.getMessage())`. – Über Lem Jan 05 '15 at 04:08

2 Answers2

0

The best way is to read all the incoming messages and append it to a string. In the below example, in the while loop, the incoming message is read into a string variable temp and the appended with line varaible. Now the line contains the full message at the end of the while loop and is set to the textView

//String variable to hold the full message
String line ="";

//String variable to hold the incoming message part
String temp;

while((temp = reader.readLine()) != null){
      //message appended to the line varable
      line.append(temp);
}

//Set the value in line to the textView here
tv.setText(line);

If still you are getting an error, you a probably catching and ignoring an error. In that case you have to observe the exception. To do that you can do something like this

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

Now you can observe the exceptions caused in your logcat.

codePG
  • 1,754
  • 1
  • 12
  • 19
  • Could you explain your answer for the OP so he might learn instead of just pasting code? – codeMagic Jan 05 '15 at 04:07
  • So i added an exception e to my catch block. Now when i look at the logcat, after entering the "http://google.com" url to my edittext and press the button, there is an exception: error null thrown. – Ali Aslam Jan 05 '15 at 04:17
  • So i may not be fully understanding this.. does the null error mean that the reader not grabbing anything? @codePG i was going to try doing that. thanks for reassuring my own thinking. – Ali Aslam Jan 05 '15 at 04:20
  • @AliAslam, not sure where the null error is caused. Have to observe the logcat. It would be nice if you could update the question with the error message – codePG Jan 05 '15 at 04:21
  • So after adding an exception and trying to find out what or where the problem is occuring, here is a snippet from the logcat as requested by @codePG – Ali Aslam Jan 05 '15 at 04:38
  • new here so apparently i need more rep to post images, so ill make a short list of what i see in the logcat 1)TAG Exception: error null 2)system err android.os.NetworkOnMainthreadexception 3)system err android.os.StrictMode$AndroidBlockGuardPolicy.OnNetwork – Ali Aslam Jan 05 '15 at 04:45
  • @AliAslam there error is due to loading URL in the main thread, you should make use of an async task. Refer the other answer given – codePG Jan 05 '15 at 04:47
0

Yep, this was an NetworkOnMainThreadException!

You cannot load URLs within the GUI thread. You need to do that stuff on a different thread. That's why AsyncTask was created.

Here is a working app based on your code which runs perfectly on my Nexus 5 (Android KitKat 4.4.4).

** EDIT ** I tried to modify the text of a TextEdit from the doInBackground() method which is not allowed. Simply commented the lines below.

package com.example.stackoverflow27773175;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity
{
    private EditText et;
    private Button pressMe;
    private TextView tv;


    private class MyAsyncTask extends AsyncTask<String, Void, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            StringBuilder sb    = new StringBuilder();
            URL url             = null;

            try
            {
                url                     = new URL(params[0]);
                URLConnection conn      = url.openConnection();
                BufferedReader reader   = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line             = "";

                while((line = reader.readLine()) != null)
                {
                    sb.append(line);
                }

            } catch (MalformedURLException e)
            {
                e.printStackTrace();

                // Not allowed! 
                //tv.setText("Exception caught: MalformedURLException");
            } catch (IOException e)
            {
                e.printStackTrace();

                // Not allowed! 
                //tv.setText("Exception caught: IOException");
            }

            return sb.toString();
        }

        @Override
        protected void onPostExecute(String result)
        {
            tv.setText(result);
        }
    }

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

         et         = (EditText) findViewById(R.id.editText1);
         pressMe    = (Button) findViewById(R.id.button1);
         tv         = (TextView) findViewById(R.id.textView1);

         pressMe.setOnClickListener(new OnClickListener()
         {
             @Override
             public void onClick(View v)
             {
                 MyAsyncTask myAsyncTask    = new MyAsyncTask();
                 myAsyncTask.execute(new String[] {et.getText().toString()});
             }
        });
    }
}

Also, make sure to specify the android.permission.INTERNET permission in your AndroidManifest.xml before the <application> tag:

<uses-permission android:name="android.permission.INTERNET" />
Über Lem
  • 343
  • 3
  • 9
  • Wait so this is mind boggling! Why does the instructor's code work? Does it have to do with him using an emulator and me using an actual device? Unless android libraries have been changed since these tutorial were first published online. If anyone can give me some insight on why his code works without him using aysnc task manager. When i did the HTTpclient tutorial, i did use the asyn task during that tutorial but not for this one. – Ali Aslam Jan 05 '15 at 04:52
  • Is there a link to your instructor's code? Android just doesn't allow URL loading on the GUI thread... your instructor must be doing something in a different thread! – Über Lem Jan 05 '15 at 04:53
  • 1
    @AliAslam http://stackoverflow.com/questions/10759054/network-in-ui-thread-in-an-android-deviceandroid-3-0-or-newer – codeMagic Jan 05 '15 at 04:55
  • @AliAslam http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – codePG Jan 05 '15 at 04:57
  • Ok so this is not the code but the version of android. I think the tutorials came out when android was beginning to gain ground meaning a long while ago. i do not have the code but my code is exactly like his letter by letter except the package name. So finish off the discussion, let me summarize the problem. URL connection cannot be done on UI activity. So any activity that is wanting connection to the internet must be done in the backgorund using async task manager. This is due to the changes in the android version 3.0 and above. – Ali Aslam Jan 05 '15 at 05:02
  • Exactly. This way, the UI does not become unresponsive and users don't become angry at you, haha – Über Lem Jan 05 '15 at 05:08
  • @Uber Lem thank you so much for the code. Its very simple to understand. and i have complied it and it works! i can see the lines read in but my textview is not set properly to display most of the content. I can fix that but i really do appreciate all the help!!! – Ali Aslam Jan 05 '15 at 05:12