How to resolve the NetworkOnMainThreadException error?

6

I'm having an error in passing the HTTP Client from JSON to Android.

Follow my code in JSON:

    // constructor
    public void JSONParser() {}

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = (InputStream) httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

}

It gives the following error in the line of HttpResponse = HttpClient.execute

06-18 12:18:54.761: E/AndroidRuntime(1090): FATAL EXCEPTION: main
06-18 12:18:54.761: E/AndroidRuntime(1090): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{br.com.example.souprogresso/br.com.example.souprogresso.retornaUsuario}: android.os.NetworkOnMainThreadException
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.os.Looper.loop(Looper.java:137)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.app.ActivityThread.main(ActivityThread.java:4424)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at java.lang.reflect.Method.invokeNative(Native Method)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at java.lang.reflect.Method.invoke(Method.java:511)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at dalvik.system.NativeStart.main(Native Method)
06-18 12:18:54.761: E/AndroidRuntime(1090): Caused by: android.os.NetworkOnMainThreadException
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at br.com.example.souprogresso.JsonParser.getJSONFromUrl(JsonParser.java:35)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at br.com.example.souprogresso.retornaUsuario.<init>(retornaUsuario.java:19)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at java.lang.Class.newInstanceImpl(Native Method)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at java.lang.Class.newInstance(Class.java:1319)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
06-18 12:18:54.761: E/AndroidRuntime(1090):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
06-18 12:18:54.761: E/AndroidRuntime(1090):     ... 11 more
06-18 12:18:55.381: I/dalvikvm(1090): threadid=3: reacting to signal 3
06-18 12:18:55.531: I/dalvikvm(1090): Wrote stack traces to '/data/anr/traces.txt'
06-18 12:18:56.041: I/dalvikvm(1090): threadid=3: reacting to signal 3
06-18 12:18:56.081: I/dalvikvm(1090): Wrote stack traces to '/data/anr/traces.txt'
06-18 12:23:55.732: I/Process(1090): Sending signal. PID: 1090 SIG: 9

My code where I bring the information

public class retornaUsuario  {

    private static String url = "http://www.xxxxxxx.com.br/SOUPROGRESSO/Ctrl/server2.php";

    JsonParser jParser = new JsonParser();
    JSONObject json = jParser.getJSONFromUrl(url);

//  @SuppressWarnings("unchecked") 
    public static void main(String[] args) throws JSONException { 
        //Retorno 
        Usuario usuario = new Usuario();

        //Retorno dos dados que precisamos 
        JSONObject json = new JSONObject(url);
        String nome = json.getString("nome");
        String cpf = json.getString("cpf");

        usuario.setNome(nome);
        usuario.setCpf(cpf);

        System.out.println(usuario); 

    }

}
    
asked by anonymous 18.06.2015 / 14:27

1 answer

5

The exception concerned, NetworkOnMainThreadException , is thrown when an application tries to perform a network in the Main thread . Android, from its version 3 (API 11), forces this type of operation to be done in a thread other than the main .

There are two solutions: easy and right.

1 - Easy to inform Android to ignore this situation.

In the% method of Activity put this code:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Note that by using it you can momentarily block user interaction with the application.

2 - The correct one, use the class AsyncTask , a Service or another any means that performs this operation on another thread .

Write a class that inherits from AsyncTask and in the onCreate method, create your class JsonParser and call the doInBackground() method.

public class RetrieveJsonTask extends AsyncTask<String, Void, JSONObject> {

    protected JSONObject doInBackground(String... urls) {

        return new JsonParser().getJSONFromUrl(urls[0])
    }

    protected void onPostExecute(JSONObject jsonObject) {

        // Usar aqui o jsonObject
        String nome = json.getString("nome");
        String cpf = json.getString("cpf");

        Usuario usuario = new Usuario();
        usuario.setNome(nome);
        usuario.setCpf(cpf);
    }
}  

To use:

private static String url = "http://www.xxxxxx.com.br/SOUPROGRESSO/Ctrl/server2.php";
new RetrieveJsonTask().execute(url);

The returned JSONObject is available in the getJSONFromUrl() method of the RetrieveJsonTask class     

18.06.2015 / 15:04