How to resolve Networkonmainthreadexception error?

Asked

Viewed 1,287 times

6

I have an error in passing the JSON HTTP Client to Android.

Follow my JSON code:

    // 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;

    }

}

Gives the following error in line 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); 

    }

}

1 answer

6

The exception in question, Networkonmainthreadexception, is launched when an application tries to run a network operation on Main thread.
Android, from its version 3(API 11), forces this type of operation to be done in another thread other than the main.

There are two solutions: easy and correct.

1 - The easy, inform the Android to ignore this situation.

In the method onCreate of Activity put this code:

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

Note that using it may momentarily block user interaction with the application.

2 - Correct, use class Asynctask or any other means that performs that operation in another thread.

Write a class you inherit from Asynctask and in the method doInBackground() create your class Jsonparser and call the method getJSONFromUrl().

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 Jsonobject returned is available in the method onPostExecute() class Retrievejsontask

Browser other questions tagged

You are not signed in. Login or sign up in order to post.