Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error StrictMode$AndroidBlockGuardPolicy.onNetwork [duplicate]

Tags:

json

android

I created android application and use JSON get data from server but I got the error show below:

android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)

how can I fix this problem
Thank you

like image 210
user3415458 Avatar asked Mar 14 '14 03:03

user3415458


2 Answers

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.

like image 135
user3113670 Avatar answered Nov 20 '22 14:11

user3113670


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.

like image 47
Arshad Ali Avatar answered Nov 20 '22 14:11

Arshad Ali