title: Get JSON object from URL using HTTPURLConnection on android
body: <p>I am currently trying to access a JSON object on my android application. However, I keep getting the following error:</p>
  
  <p>android.os.NetworkOnMainThreadException</p>
  
  <p>From researching it a bit, the only information I have currently is that I need to be doing this asynchronously(?)</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public class MainActivity extends AppCompatActivity {
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
  
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView dynamictext;
      dynamictext = (TextView) findViewById(R.id.dynamictext);
      dynamictext.setText(getJSON("my url here"));
  
  }
  
  
  public String getJSON(String url) {
      HttpURLConnection c = null;
      try {
          URL u = new URL(url);
          c = (HttpURLConnection) u.openConnection();
          c.connect();
          int status = c.getResponseCode();
          switch (status) {
              case 200:
              case 201:
                  BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                  StringBuilder sb = new StringBuilder();
                  String line;
                  while ((line = br.readLine()) != null) {
                      sb.append(line+"\n");
                  }
                  br.close();
                  return sb.toString();
          }
  
      } catch (Exception ex) {
          return ex.toString();
      } finally {
          if (c != null) {
              try {
                  c.disconnect();
              } catch (Exception ex) {
                  //disconnect error
              }
          }
      }
      return null;
  }
  }
  </code></pre>
  
  <p>Thanks in advance</p>