I am currently trying to access a JSON object on my android application. However, I keep getting the following error:
android.os.NetworkOnMainThreadException
From researching it a bit, the only information I have currently is that I need to be doing this asynchronously(?)
Here is my 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;
}
}
Thanks in advance