Solution 1 :
Networking stuff tends to brick up, since responses can take a while to travel. What it’s saying is that you need to move your code to another thread so that your program doesn’t freeze up while it’s waiting for a response.
This won’t prevent networking-related slowdowns, but it will get rid of the error:
Thread networking = new Thread(){
void run() {
int responseCode = con.getResponseCode();
}
}
networking.start();
networking.join();
Problem :
I was trying to write an app which gets some JSON from a website, converts it into an array and then puts specific elements of this array into different spots of a table in the app. I wrote the code which gets me the JSON data and converts it into an ArrayList in Eclipse. It worked great there. I now tried to implement the code in Android Studio but I just can’t get it to work. I have the following code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.table_layout);
TextView textview = (TextView) findViewById(R.id.textView8);
try{
textview.setText(MainActivity.get_data().toString());
}
catch (Exception e){
textview.setText(e.getClass().getCanonicalName());
}
}
public static ArrayList<String> get_data() throws Exception{
String[] ids = new String[] {(here are some ids)};
ArrayList<String> alldata = new ArrayList<>();
for(int r=0;r<ids.length;r++) {
String url = "https://ktrax.kisstech.ch/backend/tracking?db=aviation&sw_lat=40.97765930663377&sw_lon=-26.280096606906117&ne_lat=43.01854550507729&ne_lon=-23.407171802218617&ktrax_id=icao%3a" +ids[r]+"&format=json";
URL ktraxURL = new URL(url);
JSONArray test = Networkaccess.getJSONarr(ktraxURL);
ArrayList<String> listdata = MainActivity.converter(test);
ArrayList<String> elementlist = new ArrayList<>();
(some more code (irrelevant in this matter) which makes the array nice and neat)
//System.out.println(alldata);
return alldata;
}
public static ArrayList<String> converter(JSONArray test){ //creates an array with all the data splited
(Some code that converts JSON to ArrayList (also no problems here))
}
}
class Networkaccess{
public static JSONArray getJSONarr(URL ktraxURL) throws Exception{
HttpURLConnection con = (HttpURLConnection) ktraxURL.openConnection();
//Checking for reponse code of GET Method
con.setRequestMethod("GET");
!!!!!! int responseCode = con.getResponseCode(); //THE DEBUGGER JUMPS FROM HERE TO THE CATCH IN MAIN
System.out.println("Response Code : " +responseCode);
//Reading Data and
BufferedReader readin = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = readin.readLine()) != null) {
response.append(inputLine);
}
readin.close();
//System.out.println(response.toString());
String jsonresp = new String(response.toString());
//System.out.println(jsonresp);
JSONObject myResponse = new JSONObject(jsonresp);
JSONArray test = myResponse.getJSONArray("targets");
//System.out.println(test);
return test;
}
}
I created the new network class as the error, which was displayed in the textview field was: android.os.NetworkOnMainThreadException. However, this didn’t seem to do the job and the same error is still shown. I have no idea on how to continue from here. When debugging, the debugger always runs until the line which I marked with !!! in the code. Then it jumps to the catch exception in the main activity.
Looking forward to your answers!
Comments
Comment posted by AsyncTask
The usual answer was to use
Comment posted by TobiCode
Okay thanks for the information. I don’t really understand how this should make a difference as the MainActivity would still have to wait for the response. And why does it work flawlessly in Eclipse but not here?
Comment posted by AndrewIsOffline
If your program is doing constant communications or listening on a port, having a separate thread is the best practice. However, if it’s just a one-off thing like you’re doing, it’s fine. I personally think it should’ve been nothing more than a warning. As for Eclipse, I thought they both compiled against the same SDK. The Java SDK doesn’t have that error, so Java will gladly freeze up your program waiting for a response.