Error StrictMode$AndroidBlockGuardPolicy.onNetwork [duplicate]

Solution 1:

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.

Solution 2:

Better to use AsyncTask as mentioned here, an Alternative for just getting rid of the Exception is use :

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
}

or this :

Thread thread = new Thread(new Runnable(){
@Override
public void run() {
    try {
        //Your code goes here
    } catch (Exception e) {
       Log.e(TAG, e.getMessage());
    }
}
});
thread.start();

in your Activity where Exception occurs.

Solution 3:

Just add two lines after on create method

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