androidhttpurlconnectionandroid-webservice

HttpUrlConnection App Crashes on ICS


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.


Solution

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