0

The method sendMessage(View view) runs on clicking a button. The method is being called successfully because t.setText("Checking..."); changes the text to Checking... as expected.

The issue is that the app force closes when s= urlConnection.getResponseCode(); is not commented out. Is it because a connection is not being established or have I missed out something in code?

I am new to android programming and couldn't find a proper guide or video tutorial on web services using HttpUrlConnection. I would like to learn this before moving on to REST, SOAP or other APIs.

What have I tried?

  1. Changed URL to a sub-domain I own but it still crashes.

  2. Searched on forums and StackOverflow and came across something called AsyncTask. I am not sure if that's necessary here because I didn't find that as a requirement in Android Doc. I learnt most of the connection part from Android Doc since video tutorials didn't explain well.

    public class Main2Activity extends AppCompatActivity {

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

    }
    public void sendMessage(View view) throws IOException {
      
        TextView t=findViewById(R.id.hello2);
        t.setText("Checking...");
        URL url = new URL("http://google.com");
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {

            int s=0;
            s= urlConnection.getResponseCode();
            t.setText("Nice.");
        } finally {
            urlConnection.disconnect();
        }
     }
}

I am aware that things get easier with APIs like REST and SOAP but I would like to do it this way for learning purposes. It would be awesome if someone could guide me to a proper tutorial or blog about the same. I honestly couldn't find anything properly explained in the tutorials I referred.

Community
  • 1
  • 1
Mathews Mathai
  • 1,707
  • 13
  • 31
  • From Android's docs: *To avoid creating an unresponsive UI, don't perform network operations on the UI thread. By default, **Android** 3.0 (API level 11) and higher **requires you to perform network operations on a thread other than the main UI thread**; if you don't, a NetworkOnMainThreadException is thrown.* - **so point 2 is not true(you didn't read the doc)** – Selvin Mar 12 '18 at 15:19
  • @Selvin, Thanks a lot :D Does that mean above code will work if I use a virtual device with Android version 2.0 or less? – Mathews Mathai Mar 12 '18 at 15:23
  • Possible duplicate of [How do I fix android.os.NetworkOnMainThreadException?](https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception) – Astik Anand Mar 12 '18 at 20:45

1 Answers1

2

For sure you can't do that in this way, Why?

Because of Main Thread in android which is UI Thread, it can't do long time operation like network threads, it can't wait for it, however any explicit thread doesn't have access to the UI Thread then what should you do ?

You have to make Async Method and The httpUrlConnection should be called inside Class called AsyncTask and if you do really need to edit some component in UI thread while you are inside async method then You have to use Handlers in order to edit some of them, so your code should work only if you did something like that

new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground( Void... voids ) {
        HttpURLConnection urlConnection = (HttpURLConnection) 
        url.openConnection();
        return null;
    }
}.execute();
Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34