Android app using HttpURLConnection crashes at connect()

I have a following piece of code, basically copy-pasted from examples as I am new to Java and Android (not to programming):

      URL vurl = new URL(voteurl); //vuteurl is a string containing a proper URL
      HttpURLConnection hc;
      hc=null;
      hc = (HttpURLConnection)vurl.openConnection();
      hc.setRequestMethod("GET");
      hc.setDoOutput(true);
      hc.setReadTimeout(10000);
      hc.connect();

On the line "hc.connect();" the application crashes and Android informs me that it had been stopped. Adding android.permission.INTERNET to the permisions used by the app did not help.

Answers


OK, turns out Android doesn't like network operations in the main thread. Doing a request in a separate thread does the trick. Thanks guys for Your help!


URL vurl = null;
    try {
        vurl = new URL(voteurl);
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } //vuteurl is a string containing a proper URL
    HttpURLConnection hc;
    hc=null;
    try {
        hc = (HttpURLConnection)vurl.openConnection();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        hc.setRequestMethod("GET");
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    hc.setDoOutput(true);
    hc.setReadTimeout(10000);
    try {
        hc.connect();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Need Your Help

How to generate id for easily sorting purpose in SQL Server?

sql sql-server sorting identity

I'm making an website and I have problem generate the parent/child tree like:

A while loop to add the digits of a multi-digit number together? (Javascript)

javascript function while-loop numbers digits

I need to add the digits of a number together (e.g. 21 is 2+1) so that the number is reduced to only one digit (3). I figured out how to do that part.