Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] java – Network operation results in android.os.NetworkOnMainThreadException

Posted on November 11, 2022 By

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.

READ  [FIXED] android - Image_picker throws removeInvalidNode all the node in jank list is out of time instead of returning image
Powered by Inline Related Posts

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.

Android Tags:android, java, networking

Post navigation

Previous Post: [FIXED] java – How to handle large amount of animated vector drawables?
Next Post: [FIXED] c# – Call a self hosted web api from an Android app through a DDNS

Related Posts

[FIXED] i want to send image and some data using volley in android Android
[FIXED] java – Using AlarmManager for periodic task Android Android
[FIXED] java – Migration error while switching to new Google Maps SDK Android
[FIXED] java – How to register a Service programmatically in Android? Android
[FIXED] android – How can you create a clipped NavigationDrawer below the AppBar? Android
[FIXED] javascript – Ionic – Show Splash Screen When Switch Apps on Android Android

Archives

  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • Can Vicks humidifier be used without filter?
  • What color is Spanish green?
  • How old is Jamie in The War That Saved My Life?
  • When should I use scalp massager for hair growth?
  • Can I put polyurethane over liming wax?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme