1

I've been playing around with Android Studio and trying to establish a connection to a dev environment in which reponds back with JSON. I have tested my code and Eclipse (not ADK) and it works fine. I've added the permissions to the AndroidManifest.xml file for INTERNET and ACCESS_NETWORK_STATE so that has been covered. I dont know what else to do?

My Java:

public class GetClientDetails {

public void jsonResponse () {

    try{
        URL url = new URL("http://invsydmdev069:7080/IFXJSON?type=PartyRq&RqUID=123456789&PartyId=1093300");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader (is, "UTF-8") );

        try {

            String preJsonObj = reader.readLine();

            JSONObject jsonObj = new JSONObject(preJsonObj);
            String strPartyId = jsonObj.getJSONObject("PartyRs").getJSONObject("PartyRec").getString("PartyId");

        } catch (JSONException e) {

            throw new RuntimeException(e);
        }

    }
    catch(Exception e)
    {
        System.out.println("its fked");
    }
  }

}
ngrashia
  • 9,869
  • 5
  • 43
  • 58
mystro
  • 28
  • 2

2 Answers2

0

The android.os.NetworkOnMainThreadException is self explainatory. You are not supposed to do any network operations on Main Thread which causes UI to be non-responsive. You need to run your network operations in an AsyncTask.

Check this post on SO.

Community
  • 1
  • 1
bhargavg
  • 1,383
  • 9
  • 12
0

Android 4.+ explicitly forbids network communication in the main thread (the thread that updates the user interface). It does that to avoid freezing the UI, causing a bad user experience.

Like bhargavg said, you should wrap that code in another thread, possibly using an AsyncTask or any other strategy that uses (or creates) a new thread.

Leandro
  • 949
  • 6
  • 8