Error StrictMode$AndroidBlockGuardPolicy.onNetwork [duplicate]

you have to insert 2 lines “StrictMode” on MainActivity Class, example’s below:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        
        try {
            // JSON here
        } catch (JSONException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        setContentView(R.layout.activity_main);
        Intent intent=new Intent(this,HomeActivity.class);
        startActivity(intent);
    }
}

Aey.Sakon

Edit:
This answer “solves” the “problem”, but it does not really explain it, which is the important part.

Modifying StrictMode is NOT a fix. As well as this exception is not really an error in program logic. It is and error in program paradigm and the exception tells you, that

you should not be performing http calls on your main thread as it leads to UI freezing. As some other answers suggests, you should hand off the http call to AsyncTask class.

https://developer.android.com/reference/android/os/AsyncTask

Changing the StrictMode really just tells the app – do not remind me of me writing bad code. It can work for debugging or in some cases where you know what you are doing but generally it is not the way to go.

Leave a Comment